我正在使用strtok()来解析每个整数并将其放入int nums[1000]
。该文件将始终遵循以下格式:
第一行包含数组的数字,每个数字用空格分隔。不超过10个号码将在线上。第一行之后文件中没有任何内容。
printf("Starting program\n");
char file_name[100];
strcpy(file_name, args[1]);
char number[100];
strcpy(number, args[2]);
FILE *fp;
fp = fopen(file_name, "r");
if (fp == NULL) {
printf("Error opening file\n");
}
char int_array[1000];//
int nums[1000]; //storing the integers without spaces
int i = 0; //for indexing the array to save the integers
while (fgets(int_array, 1000, fp) != NULL) {
printf("%s\n", "test");
puts(int_array); // prints out `1 2 3 4 5...`
char *token;
token = strtok(int_array, " ");
nums[i] = atoi(token);
while (token != NULL) {
token = strtok(NULL, " ");
nums[i] = atoi(token);
//puts(token); Token gets printed out correctly.
}
}
printf("%i\n", nums[i]); // this gives segmentation fault
printf(nums) // also gives seg fault
我无法弄清楚为什么我会遇到段错误。
答案 0 :(得分:3)
您的代码存在多个问题,主要问题是您在扫描下一个标记之前测试token
:
while (token != NULL) {
token = strtok(NULL, " ");
nums[i] = atoi(token);
}
你应该这样做:
while ((token = strtok(NULL, " ")) != NULL) {
nums[i] = atoi(token);
}
其他问题:
argc > 1
中的argv[1]
之前,您不会检查是否strcpy(file_name, args[1]);
,可能会调用未定义的行为。argv[1]
传递给fopen
或使用指针:char *filename = argv[1];
fopen()
是否失败,但不退出该函数... fgets()
对于空流指针有未定义的行为。strtok()
即使是第一次通话也可以返回NULL
。请务必先检查返回值,然后再将其传递给atoi()
。i
是否变得太大。如果i
到达1000
。nums
数组传递给printf
是不正确的:printf(nums)
甚至不应该编译,或至少生成有意义的警告。请注意,您根本不需要使用strtok()
。 strtol()
可以解析数字并更新指针以指向数字。
以下是如何使用它:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
printf("Starting program\n");
if (argc < 2) {
fprintf(stderr, "missing command line argument\n");
return 1;
}
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %s\n", argv[1], strerror(errno));
return 1;
}
char buf[1000];
int nums[1000];
int i = 0;
while (fgets(buf, sizeof buf, fp)) {
char *p = buf;
char *q;
for (; i < 1000; i++) {
nums[i] = strtol(p, &q, 0);
if (q == p) {
/* no more numbers */
break;
}
p = q;
}
}
fclose(fp);
for (int j = 0; j < i; j++) {
printf("%d ", nums[j]);
}
printf("\n");
return 0;
}
答案 1 :(得分:0)
您没有检查argc
并且拒绝args[1]
和args[2]
。
您永远不会使用number
。
试试这个:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main( int argc, char * argv[] ) {
printf("Starting program\n");
if( argc < 2 ) {
return 1;
}
FILE * fp = fopen( argv[1], "r");
if( fp == NULL ) {
perror( argv[1] );
return 1;
}
char int_array[1000];
if( fgets( int_array, 1000, fp )) {
int nums[1000];
int i = 0;
char * token = strtok(int_array, " ");
while( token ) {
nums[i++] = atoi(token);
token = strtok(NULL, " ");
}
printf("0: %i\n", nums[0]);
printf("1: %i\n", nums[1]);
printf("%d: %i\n", i-1, nums[i-1]);
}
return 0;
}
执行:
aubin@Breizh-Atao ~/Dev/C $ gcc parsing.c -o parsing
aubin@Breizh-Atao ~/Dev/C $ echo 1 2 3 4 5 6 7 8 9 10 11 >parsing.txt
aubin@Breizh-Atao ~/Dev/C $ ./parsing parsing.txt
Starting program
0: 1
1: 2
10: 11
aubin@Breizh-Atao ~/Dev/C $