C语言中如何知道行尾

Sar*_*ark 4 c

如果我做 :

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?


}
Run Code Online (Sandbox Code Playgroud)

我需要知道我是否需要整行,fgets因为我有一个分隔符。

Chi*_*hip 5

根据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.
Run Code Online (Sandbox Code Playgroud)

所以,一旦fgets返回,就有3种可能

  1. 已达到 LENGTH_LINE
  2. 我们有一个换行符
  3. 已达到 EOF。

我假设您在情况 2 和 3 中排队。

本例中检测条件为:

line[len-1] == '\n' || feof(fp)
Run Code Online (Sandbox Code Playgroud)