【问题标题】:read a file for a particular input format读取特定输入格式的文件
【发布时间】:2013-09-16 13:57:37
【问题描述】:

当给定的输入格式为时如何在c中读取文件

4
5
3
a,b
b,c
c,a

请帮助...这是我的文件扫描功能。这里 m 应该存储 4,n 应该存储 5,l 应该存储 3。然后 col1 将存储{abc},col2 将存储{bca} m n , l 是整数。 col1 和 col2 是字符数组 该文件的第三行表示一个值 3 ,表示它下面有三行,包含 3 对字符。

i = 0, j = 0;
while (!feof(file))
{
  if(j==0)
  {
    fscanf(file,"%s\t",&m);
    j++;
  }
  else if(j==1)
  {
    fscanf(file,"%s\t",&n);
    j++;
  }
  else if(j==2)
  {
    fscanf(file,"%s\t",&l);
    j++;
  }
  else
  {
    /* loop through and store the numbers into the array */
    fscanf(file, "%s%s", &col1[i],&col2[i]);
    i++;
  }
}

但是我的结果没有出来,请告诉我如何继续......

【问题讨论】:

  • 文件总是6行吗?
  • 没有第三行有值 3 ,表示它下面有三行,它包含成对的字符。
  • 你做错了。删除 while 循环。然后编写代码来处理第一行。仅对以相同方式处理的行使用 while 循环(使用 col1 的行)

标签: c


【解决方案1】:

更新以允许读取可变数量的行

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  int value1, value2, value3, i;
  char *col1, *col2;
  char lineBuf[100];
  FILE* file;

  file = fopen("scanme.txt","r");

  fgets(lineBuf, 100, file);
  sscanf(lineBuf, "%d", &value1);
  fgets(lineBuf, 100, file);
  sscanf(lineBuf, "%d", &value2);
  fgets(lineBuf, 100, file);
  sscanf(lineBuf, "%d", &value3);

  // create space for the character columns - add one for terminating '\0'
  col1 = calloc(value3 + 1, 1);
  col2 = calloc(value3 + 1, 1);

  for(i = 0; i < value3; i++) {
    fgets(lineBuf, 100, file);
    sscanf(lineBuf, "%c,%c", &col1[i], &col2[i]);
  }
  fclose(file);

  printf("first three values: %d, %d, %d\n", value1, value2, value3);
  printf("columns:\n");
  for (i = 0; i < value3; i++) {
    printf("%c  %c\n", col1[i], col2[i]);
  }

  // another way of printing the columns:
    printf("col1: %s\ncol2: %s\n", col1, col2);
}

我没有执行任何通常的错误检查等 - 这只是为了演示如何读取内容。这产生了您拥有的测试文件的预期输出。我希望你能从这里拿走它。

【讨论】:

  • 这里而不是 for 循环中的 3 。如果我使用 value3 。您的代码无法正常工作。我的意思是第三行会告诉我在第三行之后会有多少个字符对 3 ,没有字符对只有 3 个。
  • 请解释一下你在说什么。这完全适用于您提供的文件(3 个数字后跟 3 行);如果您希望行数是可变的,您需要在您的问题中解释这一点。
  • 我现在明白了。我将相应地修改代码。给我一分钟。
  • 很遗憾您不喜欢我的解决方案。它仍然不适合你吗?
【解决方案2】:

几点建议:

  1. 不要使用feof(),这样的代码永远不需要它。
  2. 使用fgets() 一次阅读整行。
  3. 然后解析该行,使用例如sscanf()
  4. 检查 I/O 函数的返回值,它们可能会失败(例如在文件末尾)。

【讨论】:

    猜你喜欢
    • 2012-05-11
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2011-08-16
    • 2018-07-23
    • 2013-07-27
    相关资源
    最近更新 更多