Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can know if the end of line in C

Tags:

c

If I do :

int main(){
    const int LENGTH_LINE = 100;
    char line[LENGTH_LINE];
    int len;
    FILE* fp = fopen(file.txt,"r");

    fgets(line,LENGTH_LINE,fp);
    len = strlen(line);
    if(line[len-1] == '\n')
       printf("I've a line");

    //This work if the line have \n , but if the end line of the text dont have \n how can do it?


}

I need to know if I take a whole line with fgets because I got a delimiter.

like image 696
Sark Avatar asked Sep 12 '25 04:09

Sark


1 Answers

According to http://en.cppreference.com/w/c/io/fgets

Reads at most count - 1 characters from the given file stream and stores them in str. 
Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.

So, once fgets returns, there are 3 possibilities

  1. LENGTH_LINE was reached
  2. We got a newline
  3. EOF was reached.

I'm assuming you have a line in cases 2 and 3.

In this case the detection condition is :

line[len-1] == '\n' || feof(fp)
like image 164
Chip Avatar answered Sep 13 '25 18:09

Chip