【问题标题】:Reading an input file and ignoring blank lines or lines starting with # in C读取输入文件并忽略 C 中以 # 开头的空行或行
【发布时间】:2014-04-01 15:52:49
【问题描述】:

我正在尝试读取一个文件,该文件包含几行以 # 开头的信息,然后是数据列表。我需要对这些数据进行排序并计算行数,找到几列的最大数量,并打印我找到的每种文件类型的数量。除此之外,我需要避免空行。一个示例文件是:

# 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() 读取整行。然后使用fscanf() 将其与每个字段匹配。大多数fscanf() 格式说明符方便地忽略前导空格,这正是您想要的。

标签: c file file-io


【解决方案1】:

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

【讨论】:

  • 谢谢!我以前没有使用过 sscanf ,所以这让我很困惑。现在一切都说得通了
  • @ajay:注意:“格式中的空格...... sscanf 将......丢弃......空白字符......”是真的。但是如果格式是"%20s%d%d%20s"(没有)空格,结果会是一样的。所有格式说明符(%n %[ %c 除外)都忽略前导空格。 "%20s %d %d %20s " 的尾随空格不会影响任何内容。 +1 fgets()%20
  • @chux 很着急,所以没有注意到。是的,现在好多了。删除了所有冗余。谢谢你:)
【解决方案2】:

使用它来跳过注释行:

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

然后用它读一行:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 2022-07-29
    相关资源
    最近更新 更多