从 C 中的文本文件中读取 int 值 [英] Read int values from a text file in C

查看:24
本文介绍了从 C 中的文本文件中读取 int 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下三行的文本文件:

I have a text file that contains the following three lines:

12 5 6
4 2
7 9

我可以使用 fscanf 函数读取前 3 个值并将它们存储在 3 个变量中.但我无法阅读其余部分.我尝试使用 fseek 函数,但它仅适用于二进制文件.

I can use the fscanf function to read the first 3 values and store them in 3 variables. But I can't read the rest. I tried using the fseek function, but it works only on binary files.

请帮我将所有值存储在整数变量中.

Please help me store all the values in integer variables.

推荐答案

一个使用 fscanf 的简单解决方案:

A simple solution using fscanf:

void read_ints (const char* file_name)
{
  FILE* file = fopen (file_name, "r");
  int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
    {  
      printf ("%d ", i);
      fscanf (file, "%d", &i);      
    }
  fclose (file);        
}

这篇关于从 C 中的文本文件中读取 int 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆