我只是想用 3 个命令行参数运行这个程序:2 个整数和 1 个文件名。
我一直在运行我的程序:
a.out 1 2 devices.txt
devices.txt 看起来像这样:
1
我的主要方法是这样的:
int main(int argc, char* argv[]){
int MaxIterations, T, numDevices;
FILE *devices;
printf("Num arguments: %d \n", argc);
if(argc < 3 || argc > 4){
printf("ERROR, need exactly 2 or 3 arguments!\n");
return 1;
} else if (argc == 3){
MaxIterations = argv[1]; // max iterations allowed
T = argv[2]; // time interval
devices = fopen("devices.in", "r");
} else {
MaxIterations = argv[1];
T = argv[1];
devices = fopen(argv[3], "r");
if(devices == NULL){
fprintf(stderr, "CANT OPEN FILE: %s!\n", argv[3]);
exit(1);
}
}
FILE* file = fopen ("devices.txt", "r");
int i = 0;
fscanf(devices, "%d", numDevices);
printf("Number of devices: %d \n", numDevices);
fclose(devices);
return 0;
我做错了什么导致出现段错误? 我已经添加了调试 printf 来找出段错误实际触发的位置,它看起来像在:
fscanf(devices, "%d", numDevices);
最佳答案
启用编译器警告:
这是无效的:
fscanf(devices, "%d", numDevices);
这是你想要的:
fscanf(devices, "%d", &numDevices);
d
转换说明符需要一个指向有符号整数的指针。您正在传递(未初始化的)对象 numDevices
的值。
关于c - 从 C 中的文件读取时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14738514/