c - 为什么 fgets 卡在回车\r 上?

标签 c c99 fgets scanf carriage-return

我对论坛和一般的 c 都是新手,所以请耐心等待。我正在尝试编写一个 C 程序,它接受一个文本文件并解析所有单词和字符,然后将它们保存到输出文本文件中。我使用 C99、Windows 7-64bit、MinGW、notepad、notepad++ 和 ASNI 格式的 txt 文件。我读到 fgets() 比 fscanf 更好地读取输入,因为它具有缓冲区溢出保护,所以我决定尝试使用它,但它在测试文件中的一些标点符号上存在问题(我认为这是回车符)\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]='\0'; //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() 挂起?它很好地获得了第一行,然后就卡住了。

预先感谢您花时间查看此内容。如果您对我的代码有任何其他建议,请随时告诉我。

最佳答案

“当读取 flimit 个字符、在 filein 中或在文件末尾遇到第一个换行符(以先到者为准)时,fgets 函数将停止读取。”

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

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

...

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

...

以下链接通过示例解释了 fgets 函数的正确用法。

引用:http://pubs.opengroup.org/onlinepubs/009695399/functions/fgets.html

希望对你有帮助

关于c - 为什么 fgets 卡在回车\r 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34253808/

相关文章:

无法获得一行的正确输出

c - C99 中 'unlocked' I/O 函数的等价物是什么?

c - fscanf 不在变量中放置值

c - 为什么 fgets 在程序关闭和从 tail -f 传输数据时挂起?

c - _C99的Bool数据类型

c - 传递 'fgets' 的参数 1 使指针来自整数而不进行强制转换

c++ - 与 C 代码相比,为什么 C++ 代码不需要 "#define _POSIX_C_SOURCE 200809L"?

c - 开发一个函数,返回数组中存在的不同值的数量

c - 内存和文件指针

通过相应标准 I/O 流的输入/输出是否会失败?