所以我目前正在为我的代码收到Segmentation错误,并试图缩小它的范围。我不确定fgetc
函数的起点是否跟fprintf
和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
答案 0 :(得分:0)
循环中的fgetc
调用将从fscanf
完成的位置开始,但您应该知道此点将位于扫描完最后一项之后的下一个字符处。假设它工作正常,那将是第二行末尾的\n
字符(假设你在前一行的那一行开始,这似乎是你的代码注释的情况)。
因此,第一个fgetc
将为您提供上述\n
,下一个将在第三行的开头为您提供'I'
,依此类推。
如果您遇到崩溃,我会立即检查一些事情。
首先,c
是int
类型而不是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
]