我试图通读一个文件,其中包含以#开头的几行信息,然后是数据列表。我需要对这些数据进行排序并计算行数,找到最少数量的列,并打印我找到的每种文件类型的数量。除此之外,我还需要避免空行。示例文件将是:
# Begin
# File | Popularity | Uses | Name
asdf.exe | 4 | 280 | asdf
firefox.exe | 1 | 3250 | firefox.exe
image.png | 2 | 2761 | image
start | 5 | 100 | start
font.txt | 6 | 20 | font
smile.txt |3 | 921 |smile
注意:|代表长度不确定的空白
我在尝试考虑列之间的空格以及分隔每行内的整数和字符串以及计算#和空行时遇到了很多麻烦,所以我真的很感激任何建议,因为我被卡住了。我不想要任何实际的代码,但想要开始。
答案 0 :(得分:2)
您应该使用fgets
来读取文件中的行。您可以检查'#'
或'\n'
行的第一个字符并进行相应处理。
// max length of a line in the file
#define MAX_LEN 100
char linebuf[MAX_LEN];
// assuming the max length of name and filename is 20
char filename[20+1]; // +1 for the terminating null byte
char name[20+1]; // +1 for the terminating null byte
int p; // popularity
int u; // uses
FILE *fp = fopen("myfile.txt", "r");
if(fp == NULL) {
printf("error in opening file\n");
// handle it
}
while(fgets(linebuf, sizeof linebuf, fp) != NULL) {
if(linebuf[0] == '#' || linebuf[0] == '\n')
continue; // skip the rest of the loop and continue
sscanf(linebuf, "%20s%d%d%20s", filename, &p, &u, name);
// do stuff with filename, p, u, name
}
请注意,格式字符串中的%d
转换说明符会读取并丢弃任意数量的前导空格字符。
答案 1 :(得分:0)
用它来跳过评论行:
while(fscanf(file, "%1[#]%*[^\n]\n") > 0) /**/;
然后用它来读一行:
int ret = fscanf(file, "%s %d %d %s\n" ...)
阅读任何行后,重复评论munger。