if my input is something similar to this:
4 2 3 5
2 3 5 1
3 7 8 1
6 8 1 4
and I would like to create an array with 4, 2, 3, and 6. How could I only read them from the file instead of reading the other numbers too? I would also like to sort them from smaller to bigger after that.
CodePudding user response:
You can write for example
fscanf( fp, "%d", &num );
for ( size_t i = 0; i < 3; i ) fscanf( fp, "%*d" );
for each line of the text file.
To sort an array you can use standard C function qsort
declared in the header <stdlib.h>
.
CodePudding user response:
Best way is to use fgets
to get each line, the sscanf
to scan just the first value, like this:
FILE fp = fopen("testfile.txt","r");
char line[80];
int value;
if (!fp) {
perror("opening file");
exit(1);
}
if (!fgets(line,sizeof(line),fp)) {
perror("reading file");
exit(2);
}
sscanf(line," %d ",&value);
You'll probably want the fgets
and sscanf
in a loop to read the whole file.