明らかな理由もなく、セグメンテーション違反が発生しています。関数を使用して、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;
}