Reputation: 327
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. 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.
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);
Upvotes: 1
Views: 818
Reputation: 3990
Its very simple if you know how fscanf works (and returns):
while( fscanf(fp, "%d%d%d", &tmpUI, &tmpAC, &tmpPC) == 3 )
{
...
}
Upvotes: 0
Reputation: 144969
You are not the only one asking about this assignment. Try a simpler approach:
fgets()
,sscanf(str, "%d%d%d", &a, &b, &c);
and check the return value, it should be 3
.There might be extra problems to watch for:
int
type.Upvotes: 3