【发布时间】:2016-03-31 04:37:31
【问题描述】:
我正在制作一个可以逐行读取文件的简单程序。文件的每一行都采用以下格式:整数、整数、字符。例如,对于一个看起来像这样的文件:
1 2 A
2 3 B
程序的预期输出应该是:
1 2 A
2 3 B
但它正在打印
0 2 A
0 3 B
我该如何解决?
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <stdint.h>
#include <time.h>
int main(int argc, char** argv) {
char const* const fileName = argv[1];
FILE* file = fopen(fileName, "r");
char str[1];
int key;
int val;
while (fscanf(file, "%d %d %s\n", &key, &val, str) != EOF) {
printf("Read Integer %d \n", key );
printf("Read Integer %d \n", val );
printf("Read String %s \n", str );
}
fclose(file);
return(0);
}
【问题讨论】:
-
你读取了两个整数,所以需要
"%d %d"...这样的格式 -
您正在覆盖您的
str数组。即使只输入一个字符,也会写入两个(字符,后跟一个空字节)。当然,如果输入了多个字符,那就更糟了。就目前而言,您会受到未定义行为的影响,因此所有赌注都已取消。