0

所以我目前的代码出现分段错误,并试图缩小它可能是什么。我不确定fgetc函数的起点是否与fprintfand的定位相同scanf

即,如果我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  
4

1 回答 1

0

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

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

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

第一个是ctypeint而不是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
]
于 2015-05-18T04:40:19.090 回答