[英]how do i read file of ints and store in variables in c
Ive just started c programming. 我刚刚开始编程。
I would like to read a file of ints which are in a text file in the format 我想读取格式文本文件中的整数文件
int1(space)int2(space)int3
int4(space)int5(space)int6
int7(space)int8(space)int9
data file example (actually has 25 million lines)
1000002 1 55
1000002 1000006 33
1000002 1000007 8
i am trying to read the numbers and each line i would like to store the 3 ints into a separate variable so i can create a struct with 3 ints per struct. 我试图读取数字和每行我想将3个整数存储到一个单独的变量中,这样我就可以创建一个每个结构有3个整数的结构。 I have a function to create the structs however i don't know how to read the numbers in line by line then assign each 3 ints into a temp variable. 我有一个函数来创建结构但是我不知道如何逐行读取数字然后将每个3个整数分配给临时变量。
I will be using dynamic allocation to store the structs so just array as temp storage 我将使用动态分配来存储结构,所以只是数组作为临时存储
FILE *fp = fopen("uboss.txt", "r");
//char text[255];
int i = 1;
int a = 1;
int numberArray[9999];
int tmpUI = 0;
int tmpAI = 0;
int tmpPC = 0;
if (fp == NULL)
{
printf("Error Reading File\n");
exit (0);
}
while (!feof(fp))
{
fscanf(fp, "%d ", &numberArray[i]);
printf("Number %d: %d\n",i,numberArray[i]);
tmpUI = numberArray[a];
tmpAI = numberArray[a+1];
tmpPC = numberArray[a+2];
i++;
}
fclose (fp);
You are not the only one asking about this assignment. 你并不是唯一一个询问这项任务的人。 Try a simpler approach: 尝试一种更简单的方法:
fgets()
, 在循环中,使用fgets()
读取每一行, sscanf(str, "%d%d%d", &a, &b, &c);
然后用sscanf(str, "%d%d%d", &a, &b, &c);
扫描该行3个整数sscanf(str, "%d%d%d", &a, &b, &c);
and check the return value, it should be 3
. 并检查返回值,应为3
。 There might be extra problems to watch for: 可能还有其他问题需要注意:
int
type. 如果值大于int
类型中的值,该怎么办? Its very simple if you know how fscanf works (and returns): 如果您知道fscanf如何工作(并返回),这非常简单:
while( fscanf(fp, "%d%d%d", &tmpUI, &tmpAC, &tmpPC) == 3 )
{
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.