c - 读取特定输入格式的文件

标签 c

当给定的输入格式为时如何用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++;
  }
}

但是我的结果没有出来请告诉我如何进行....

最佳答案

已更新以允许读取可变行数

#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);
}

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

关于c - 读取特定输入格式的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18829873/

相关文章:

c - tracepoint/syscalls/sys_enter 不触发 bpf_trace_printk

c - 通用列表操作函数是如何编写的?

c - 本地指针, `static` 指针和 `malloc` 指针

c - 嵌入式系统调试——我应该使用输出/日志文件吗?

C语言编程实现全大写全小写转换

c - 信号处理程序不会看到全局变量

C11 VLA 矩阵访问

c - 与 RPi 的 RS-232 通信

c++ - objdump 和 objcopy 作为 c/c++ 库

c - "C"用分隔符按空格分割字符串,但在某些单词之间转义空格(姓氏、名字)