为什么 fgets 会卡在 return \r 上?

Why is fgets getting stuck on carriage return \r?

我是论坛的新手,也是 c 的新手,所以请多多包涵。我正在尝试编写一个 c 程序,它接受一个文本文件并解析所有单词和字符,然后将它们保存到输出文本文件中。我正在为 txt 文件使用 C99、Windows 7-64 位、MinGW、notepad、notepad++ 和 ASNI 格式。我读过 fgets() 比 fscanf 更适合用于读取输入,因为它具有缓冲区溢出保护,所以我决定尝试使用它,但测试文件中的一些标点符号有问题(我认为它是回车 return\r)。我尝试使用 fscanf,除了它跳过所有空白(我可以稍后添加回来,不关心那个),它似乎很好地接收所有文本并将其打印在输出文件中。

这是我的测试代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

void main(int argc, char* argv[])
{
    int limit=100, flimit=0, flimitmax=1900000000; //I stopped flimitmax short of the 2GB mark 
    char name[limit], copyname[limit];
    FILE *data, *output;

//Gets the value of a specified data file for reading   
    printf("\nPlease specify a file to format for data input.  NOTE: CHARACTERS LIMITIED TO %d\n", limit);
    fgets(name, limit, stdin); //takes input of size 'limit' and assigns it to 'name'
    size_t ln = strlen(name);   //gets the size of name[]
    if(name[ln-1]=='\n') name[ln-1]='[=11=]'; //gets rid of newline character read in by fget
    strncpy(copyname, name, limit); //stores the value of the specified file name for use making the input and output files 
    strcat(name, ".txt"); //appends .txt file extension to the file name
    printf("\nYou chose file %s\n", name);

    data = fopen(name, "r"); //Checks to see if the specified data file exists and if it can be read
    if(data==NULL)
    {
        fprintf(stderr, "\nCan't open file %s!!!\n", name);
        exit(1);
    }

//Gets the size of the data file being worked.  Used later when the file is copied into the program using fgets.    
    fseek(data, 0, SEEK_END); // seek to end of file
    flimit = ftell(data)+1; // get current file pointer
    fseek(data, 0, SEEK_SET); // seek back to beginning of file
    if((flimit > flimitmax) || (flimit < 0))//Checks to see if flimit falls between 0 and 1.9GB.  If not, the file is larger than 1.9GB
    {
        printf("Error, max file size exceeded.  Program terminating\n");
        exit(1);
    }
    printf("File size is %d bytes\n", flimit);

//Creates a name for the output file
    strncpy(name, copyname, limit); //reassigns original value to name to make output file name
    strcat(name, "OUT.txt"); //appends OUT.txt file extension to the file name
    printf("\nOutput file is %s\n", name);

    output = fopen(name, "w"); //checks to see if the Input file exists and if it can be read
    if(output==NULL)
    {
        fprintf(stderr, "\nCan't open file %s!!!\n", name);
        exit(1);
    }

//Reads the data file and assigns values to the input and output files  

    char filein[flimit]; //I created this variable here to avoid issues of array resizing.
    //fgets attempt
    fgets(filein, flimit, data); //scans the whole datafile and stores it in the char array.

    printf("\n%s\n", filein);
    fprintf(output, filein);

    memset(&filein[0], 0, sizeof(filein)); //clears the filein array

    fseek(data, 0, SEEK_SET); // seek back to beginning of file 
    //fscanf attempt
    while(fscanf(data, "%s", &filein)!=EOF)
    {
        printf("\n%s\n", filein);
        fprintf(output, filein);
    }

//Closes the files and ends the program
    printf("\nDONE!!!\n");
    fclose(data);
    fclose(output);
}

这是我在数据文件中使用的文本:

Things/Words and punctuation:  The Test

This is a test (mostly to see if this program is working).

这是我从输出文件中得到的输出:

Things/Words and punctuation:  The Test
Things/Wordsandpunctuation:TheTestThisisatest(mostlytoseeifthisprogramisworking).

为什么 fgets() 会挂起?它得到第一行就好了,然后就卡住了。

提前感谢您抽出宝贵时间查看此内容。如果您对我的代码有任何其他建议,请随时告诉我。

"The fgets function will stop reading when flimit characters are read, the first new-line character is encountered in filein, or at the end-of-file, whichever comes first."

您的 fgets() 遇到换行符并停止。这就是为什么你需要使用 while 循环来保持你的代码 运行 直到你到达文件末尾。成功完成后,fgets() returns 一个流。如果此流位于文件末尾,则 fgets() returns 一个空指针。

以下代码块解决了您的问题,

...

    while(fgets(filein,flimit,data) != NULL)
    {
        printf("%s\n",filein);
        fprintf(output,filein);
    }

...

下面link举例说明fgets函数的正确用法

参考:http://pubs.opengroup.org/onlinepubs/009695399/functions/fgets.html

希望对您有所帮助,