C Programming Read File Line by Line Into Array
-
C: read File into Array
Hello,
I am attempting to read a file into an array on C:
Code:
#include <stdio.h> #include <stdlib.h> /*How to read a file into an array*/ int chief() { double array[29999]; double fourth dimension; FILE *fp; unsigned int i = 0; fp = fopen("alpha2.99","r"); if (fp != Aught) { while (!feof(fp)) { fscanf(fp,"%lf %lf",&time,&assortment[i]); printf("%lf\northward",assortment[i]); i++; } } fclose(fp); render 0; }
Code:
0.0 45.344 0.ane 47.464 ... 2999.9 224.879 3000.0 245.080
Lawmaking:
244.555000 245.338000 224.879000 245.080000 0.000000
Lawmaking:
244.555000 245.338000 224.879000 Segmentation fault (core dumped)
Thanks for your expertise!
-
Re: C: read File into Array
Use of feof() tin can be a chip tricky at first. Here's what happens in your instance: the get-go lines are read unremarkably. When the concluding line is read, the end-of-file indicator is Non fix. This is considering your program just reads until the last newline grapheme. It does not "look" after it, and so it does not know that there is nada and that the line is in fact the last line of the file. Thus later on it has read the last line, it enters the loop one more than time, and this is where it sees that at that place is nothing more than to read, and sets the end-of-file indicator.
One possible solution would be to check with the return falue of fscanf(). Something like
Lawmaking:
while (!feof(fp)) { if (fscanf(fp,"%lf %lf",&time,&array[i]) != 2) { go along; } printf("%lf\n",array[i]); i++; }
Concluding edited past Bachstelze; July 15th, 2012 at 10:30 PM. Reason: Posted lawmaking
-
Re: C: read File into Array
Originally Posted past Bachstelze
thank you for your reply! It works!
And then fscanf only works if it does not return a value of two? I tried writing a program to return the value of fscanf, but it didn't work:
Code:
#include <stdio.h> #include <stdlib.h> int main() { FILE *fp; fp = fopen("alpha2.99","r"); int i, time, tor; while (!feof(fp)) { i = fscanf("%lf %lf",&fourth dimension, &tor); } fclose(fp); printf("%d\n",i); return 0; }
-
Re: C: read File into Array
Originally Posted by hailholyghost
-
Re: C: read File into Assortment
Cheers so much! I wish I were able to help yous out Bachstelze, lol. If only I could.
The return value is the number of arguments co-ordinate to the man page.
Merci!
-
Re: C: read File into Array
Originally Posted by hailholyghost
RETURN VALUE
These functions render the number of input items successfully matched and assigned, which can be fewer than provided for, or even cipher in the outcome of an early matching failure.
Source: https://ubuntuforums.org/showthread.php?t=2026618
0 Response to "C Programming Read File Line by Line Into Array"
Post a Comment