我没有明显的原因得到分段错误。我正在使用该strtok
函数并将每一行拆分为多个标记并将它们存储在 char 指针中。我的数据如下所示:
输入:
200 -> 103 [weight=7];
200 -> 153 [weight=27];
200 -> 53 [weight=9];
200 -> 178 [weight=43];
55 -> 2 [weight=23];
55 -> 14 [weight=50];
55 -> 20 [weight=17];
55 -> 22 [weight=1];
55 -> 74 [weight=7];
55 -> 93 [weight=9];
55 -> 122 [weight=27];
65 -> 8 [weight=27];
65 -> 9 [weight=9];
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char **argv)
{
char *ipfile,line[80];
FILE *fp;
char *field1,*field2,*field3,*field4,*field5,*field6,mystr[10];
int row,column,weight;
ipfile = (char *)argv[1];
printf("The input file name is %s\n",ipfile);
fp = fopen(ipfile,"r");
if(fp ==NULL) //Checking whether the command line argument was correctly or not.
printf("There is no such file in the directory.\n");
while(fgets(line,80,fp) != NULL)
{
field1 = strtok(line," ");
//row = atoi(field1);
field2 = strtok(NULL," ");
field3 = strtok(NULL," ");
//column = atoi(field3);
field4 = strtok(NULL," ");
field5 = strtok(NULL," ");
//field6 = strtok(NULL," ");
printf("%s\n",field5);
//printf("Row-%d Column - %d Weight - %d\n",row,column,weight);
}
fclose(fp);
return 0;
}
来自评论:
当我尝试打印
field1
,field2
, 时field3
,field4
它们正在被打印。但是当我尝试field5
并且field6
我的程序出现分段错误时。
在 SO 用户的建议之后添加代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char **argv)
{
char *ipfile,line[80];
FILE *fp;
char *field1,*field2,*field3,*field4,*field5,*field6,mystr[10];
int row,column,weight;
ipfile = (char *)argv[1];
printf("The input file name is %s\n",ipfile);
fp = fopen(ipfile,"r");
if(fp == NULL) //Checking whether the command line argument was correctly or not.
printf("There is no such file in the directory.\n");
while(fgets(line,80,fp) != NULL)
{
field1 = strtok(line," ");
//row = atoi(field1);
field2 = strtok(NULL," ");
field3 = strtok(NULL," ");
//column = atoi(field3);
field4 = strtok(NULL," ");
field5 = strtok(NULL," []=;");
//field6 = strtok(NULL," ");
printf("%s\n",field5);
//printf("Row-%d Column - %d Weight - %d\n",row,column,weight);
}
fclose(fp);
return 0;
}