开发者

detect EOL in C using fgets

I'm attempting to read a single line from a file using the following...

 while(fgets(c,BUF,f) != EOL){
   puts(c);
 }

Where EOL = #define EOL '\n' however, I get the warning... comparison between pointer and integer

What is the correct way to achieve what I'm trying开发者_StackOverflow社区?


fgets reads a string, and the result type is char*

I'd think you are thinking of fgetc instead?


Why don't you try fgetc instead? Then you can compare the ASCII code of '/n' like this

while (fgetc (file) != '\n'){
  puts(c);
}


You need to dereference the returned char* and compare that to your EOL ... not compare the actual pointer address itself to the end-of-line character.

Change your code to this:

char* return_val = NULL;
while((return_val = fgets(c,BUF,f)) != NULL && *return_val != EOF)
{
   puts(c);
}

if (retun_val == NULL)
{
    //handle error
}


You have to examine the contents of c after the call to fgets to determine if a newline was included in the returned string:

for (;;) {
 if (fgets(c, BUF, f) == NULL) { /* handle error */ }
 if (strchr(c, EOL) != NULL) {
  puts(c);
 } else {break; }
}


fgets reads characters from the stream and writes them in the buffer until either the buffer is almost full or it finds a '\n' (it returns NULL if the operation fails).

So you can know how many characeters were read (including the '\n') with strlen ...

ret = fgets(buffer, sizeof buffer, stdin);
if (ret == NULL) /* deal with error */;
chars = strlen(buffer);

Now, one of 2 things may have hapenned: either a '\n' was read before the buffer got full or the buffer gor full before a '\n' was read. You can know which was it by examining the last character in the buffer

if (buffer[chars - 1] == '\n') /* full line read */;
else /* incomplete line */;

Note that chars is always (*) 1 or more, so the expression buffer[chars - 1] is ok.

(*) it could be 0 only with binary data for input, but that denies the use of strlen and other string functions.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜