开发者

problem with blank rows when reading from file in c

开发者 https://www.devze.com 2023-01-11 06:16 出处:网络
hello i am progremming in c with linux enviroment and facing a difficulty with blank rows whi开发者_JAVA技巧le reading from afile.

hello i am progremming in c with linux enviroment and facing a difficulty with blank rows whi开发者_JAVA技巧le reading from afile. i am using strtok function for seperating the string with delimiter "," and getting segmentation error whenever the file that i am reading from contains blank lines thanks in advance


You seem to be getting the error because you're passing an invalid parameter to strtok - Try checking that the line isn't empty before passing it to strtok.

A more robust solution would be to check that the line read from the file complies with your data format before parsing it - eg with a regex


Here's a small program that uses strtok() to parse lines with comma separated values. It may help you see what's going on (such as the problem with empty fields that Gilles brought up). It'll also help you see what happens with blank lines.

Compile it and feed it example data, either with the keyboard or by redirecting a data file to it:

#include <stdio.h>
#include <string.h>

char* myGetLine( char* buf, size_t bufSize, FILE* strm)
{
    char* result = fgets( buf, bufSize, strm);

    int len = result ? strlen(result) : 0;

    if (len && result[len - 1] == '\n') {
        // get rid of the pesky newline
        result[len - 1] = '\0';
    }

    return result;
}

int main(void)
{
    char line[80];

    while (myGetLine( line, sizeof(line), stdin)) {
        int i = 0;
        char* token = NULL;

        printf( "%s\n", line);

        token = strtok( line, ",");
        while (token != NULL) {
            printf( "token %d: \"%s\"\n", i, token);
            ++i;
            token = strtok( NULL, ",");
        }

        printf( "%s\n", "enter a new line (or EOF)");
    }

    return 0;
}


I think, regex is to big for this little homework; you have only 2 parts to do:

  • File/String I/O: e.g. take "size_t getline(char *s,size_t lim)" from here: link text
  • data processing: ',' separated columns e.g. here link text

and now its short and easy, or?

char line[100];
FILE *f=fopen(...,"rt");
if(!f) ...
while( fgets(line,sizeof line,f) )
  if( getline(line,sizeof line) ) 
  { /* no empty lines here */
    char *p,*t;
    for(puts("new line"),t=mystrtok(&p,line,',');t;t=mystrtok(&p,0,','))
      puts(*t?t:"empty column"); /* also empty columns here */
  }
fclose(f);


My suggestion is to write a line stripping function that removes any whitespace from the beginning and end of a line. Run every line through this function before processing it. Now, any blank lines should just end up being a single '\0' character.

Line stripping functions are easy to write, all you need is a pair of pointers and isspace() from ctype.h.

0

精彩评论

暂无评论...
验证码 换一张
取 消