C语言 从 C 中的文本文件中读取 int 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4600797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read int values from a text file in C
提问by elh mehdi
I have a text file that contains the following three lines:
我有一个包含以下三行的文本文件:
12 5 6
4 2
7 9
I can use the fscanffunction to read the first 3 values and store them in 3 variables. But I can't read the rest.
I tried using the fseekfunction, but it works only on binary files.
我可以使用该fscanf函数读取前 3 个值并将它们存储在 3 个变量中。但我无法阅读其余部分。我尝试使用该fseek函数,但它仅适用于二进制文件。
Please help me store all the values in integer variables.
请帮我将所有值存储在整数变量中。
回答by Vijay Mathew
A simple solution using fscanf:
一个简单的解决方案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);
}
回答by MAK
How about this?
这个怎么样?
fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2);
In this case spaces in fscanfmatch multiple occurrences of any whitespace until the next token in found.
在这种情况下,空格fscanf匹配多次出现的任何空格,直到找到下一个标记。

