c - 如何将文件中的逗号分隔行拆分为 C 中的变量?

标签 c file

如果我有一个文件,其中一行包含 12,1,如何拆分数字并将它们放入 2 个变量中?例如,变量 a 将获取 12 ,另一个变量 b 将获取 1

最佳答案

第一种方法:

我们使用fscanf()我们输入我们期望文件具有的格式。我们循环,直到函数的返回值小于我们期望读取的数字。

#include <stdio.h>

int main(void)
{
  FILE *fp;
  if ((fp = fopen("test.txt", "r")) == NULL)
  { /* Open source file. */
    perror("fopen source-file");
    return 1;
  }
  int a, b;
  while(fscanf(fp, "%d,%d", &a, &b) == 2)
  {
    printf("%d %d\n", a, b);
  }
  fclose(fp);
  return 0;
}
<小时/>

第二种方法:

我们和fgets()一起阅读进入缓冲区,然后我们在 strtok() 的帮助下进行分割,使用分隔符(本例中为逗号)。

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

#define bufSize 1024

int main(void)
{
  FILE *fp;
  char buf[bufSize];
  if ((fp = fopen("test.txt", "r")) == NULL)
  { /* Open source file. */
    perror("fopen source-file");
    return 1;
  }
  char* pch;
  int a, b, i;
  while (fgets(buf, sizeof(buf), fp) != NULL)
  {
    i = 0;
    // eat newline
    buf[strlen(buf) - 1] = '\0';
    pch = strtok (buf,",");
    while (pch != NULL)
    {
      // read first number
      if(!i++)
        a = atoi(pch);
      else // read second number
        b = atoi(pch);
      pch = strtok (NULL, ",");
    }
    printf("%d %d\n", a, b);
  }
  fclose(fp);
  return 0;
}

代码基于我的示例 here .

<小时/>

两个示例都假设我们有 test.txt,如下所示:

1,2
3,4

PS - 确保下次你表现出一些努力。 :)

关于c - 如何将文件中的逗号分隔行拆分为 C 中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27786911/

相关文章:

iphone - 在计算角度时避免使用 atan2 - atan2 精度

c - 在c中定位数组中的颜色

c - 将 C 结构转换为另一个元素较少的结构是否安全?

javascript - 使用javascript或html5编辑txt文件

java - java中的File.delete是否执行文件锁定?

C++ 读取文件失败 - g++11 - Ubuntu14

linux - 如何在 Rust 中获取打开的 std::fs::File 的文件名?

将二进制补码转换为符号数值

c - 包含c文件和在C中作为参数给出有什么区别?

java - 创建文件夹然后在该文件夹中创建文件时遇到问题