fgetc c的起点

时间:2014-03-29 00:28:36

标签: c fgetc

所以我目前正在为我的代码收到Segmentation错误,并试图缩小它的范围。我不确定fgetc函数的起点是否跟fprintfscanf的定位相同。

即如果我在文件上使用scanf然后使用fgetc,它会从一开始就开始,还是会在scanf停止的地方继续?如果是前者,我将如何操纵起点?

//reads the second line of the input file in order to grab the ten numbers in the line
int numRead = fscanf(Data, "\n %d %d %d %d %d %d %d %d %d %d", &zero, &one,
        &two, &three, &four, &five, &six, &seven, &eight, &nine); 

while(EOF != (c = fgetc(Data)))
{
  message[i] = c;
  i++;
}

输入文件:

 0  1  2  3  4  5  6  7  8  9  
 6  7  8  0  1  9  5  2  3  4  
If I were reincarnated, I'd want to come back a  
buzzard. Nothing hates him or envies him or wants  
him or needs him. He is never bothered or in  
danger, and he can eat anything.  
-- Mark Twain  

1 个答案:

答案 0 :(得分:0)

循环中的fgetc调用将从fscanf完成的位置开始,但您应该知道此点将位于扫描完最后一项之后的下一个字符处。假设它工作正常,那将是第二行末尾的\n字符(假设你在前一行的那一行开始,这似乎是你的代码注释的情况)。

因此,第一个fgetc将为您提供上述\n,下一个将在第三行的开头为您提供'I',依此类推。

如果您遇到崩溃,我会立即检查一些事情。

首先,cint类型而不是char。这是必需的,以便您可以从加上 char指示符接收任何有效的EOF类型。

第二个是message足以保存数据。

第三是i初始化为零。

为了安全起见,您可能还应检查您的扫描是否能够读取十个数字。

查看以下完整程序,了解如何执行此操作。您还要注意我还要检查以确保缓冲区不会因文件中的数据太多而溢出:

#include<stdio.h>

int main(void)
{
    // Open file for reading.

    FILE *Data = fopen ("qq.in", "r");
    if (Data == NULL) {
        puts ("Cannot open qq.in");
        return 1;
    }

    // Skip first and second line (twenty numbers).

    int zero, one, two, three, four, five, six, seven, eight, nine;

    int numRead = fscanf(Data, "%d %d %d %d %d %d %d %d %d %d", &zero, &one,
        &two, &three, &four, &five, &six, &seven, &eight, &nine);
    if (numRead != 10) {
        puts ("Could not read first ten integers");
        fclose (Data);
        return 1;
    }

    numRead = fscanf(Data, "%d %d %d %d %d %d %d %d %d %d", &zero, &one,
        &two, &three, &four, &five, &six, &seven, &eight, &nine);
    if (numRead != 10) {
        puts ("Could not read second ten integers");
        fclose (Data);
        return 1;
    }

    // Loop for reading rest of text (note initial newline here).

    int c, i = 0;
    char message[1000];

    while(EOF != (c = fgetc(Data))) {
        if (i >= sizeof(message)) {
            puts ("Too much data");
            fclose (Data);
            return 1;
        }
        message[i++] = c;
    }

    fclose (Data);

    printf ("[%*.*s]\n", i, i, message);

    return 0;
}

运行时,会产生:

[
If I were reincarnated, I'd want to come back a
buzzard. Nothing hates him or envies him or wants
him or needs him. He is never bothered or in
danger, and he can eat anything.
-- Mark Twain
]