我正在尝试使用单行“00:612:33188”读取文件“data.txt”(每个数字代表一个数据字段,“changes:size:permission”),并将该信息写入结构。我想为这些字段中的任意数量的字符编写代码。
我的问题是关于 fscanf 的使用。我似乎无法让它发挥作用。以下代码产生分段错误错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXHITS 50
#define FIELDMAX 100
#define TOTALELEMENTS 100000
typedef struct Elements{
char changes[FIELDMAX];
char size[FIELDMAX];
char permission[FIELDMAX];
} Elements;
int main(int argc, char const *argv[]) {
if(argc < 2) {
printf("\nSyntax: fscanf data\n\n");
exit(EXIT_FAILURE);
}
Elements total[TOTALELEMENTS];
Elements hits[MAXHITS];
int total_elements = 0;
int total_hits = 0;
FILE *fp;
// open the file and scan each field copying to the corresponding struct
fp = fopen (argv[1], "r");
if (fp){
fscanf(fp,"%99s:%99s:%99s", total[total_elements].changes,
total[total_elements].size, total[total_elements].permission);
printf("%s\n%s\n%s\n", total[total_elements].changes,
total[total_elements].size, total[total_elements].permission);
fclose (fp);
}
return 0;
}