繁体   English   中英

读取输入文件并忽略空白行或C中以#开头的行

[英]Reading an input file and ignoring blank lines or lines starting with # in C

我正在尝试通读具有以#开头的几行信息,然后是数据列表的文件。 我需要对这些数据进行排序并计算行数,找到几列中的最大数目,并打印找到的每种文件类型中的多少。 与此同时,我需要避免空白行。 一个示例文件将是:

# 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

注意: 代表长度不确定的空白

我在尝试解释各列之间的空格以及在每行中分隔整数和字符串以及解释#和空行时遇到了很多麻烦,因此我非常感谢任何建议,因为我被卡住了。 我不想要任何实际的代码,但可以开始构想。

您应该使用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转换说明符读取并丢弃任何数量的前导空白字符。

使用它跳过注释行:

while(fscanf(file, "%1[#]%*[^\n]\n") > 0) /**/;

然后使用它来读取一行:

int ret = fscanf(file, "%s %d %d %s\n" ...)

读完任何一行后,重复评论munger。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM