Hi, How to read line by line of text file and store to array C

data.txt example

1234	       25500	24000	1
1345	       23523	21209	5
9865	       12389	   600	98
....

and sorted in order by last column
I try everything and it not working

Thank

Edited 5 Years Ago by guidely: n/a

Hi, How to read line by line of text file and store to array C

data.txt example

1234	       25500	24000	1
1345	       23523	21209	5
9865	       12389	   600	98
....

and sorted in order by last column
I try everything and it not working

Thank

Well, Can you show us what you tried?

and sorted in order by last column

I don't have a clue what you're talking about. That's why I'm saying, post your code here, that'll explain everything for you.

I can do only read first element and store to array the rest I just struct :(

#include <stdio.h>
#include <stdlib.h> /* required for atoi */

int main(void) {
    int  i=0,totalNums;
    double numbers[100];
    double atof ( const char * str ); 
    char line[100];  /* declare a char array */
    
    FILE *file;  /* declare a FILE pointer  */
    file = fopen("data.txt", "r");  /* open a text file for reading */
    
    while(fgets(line, sizeof line, file)!=NULL) {       /* keep looping until NULL pointer... */
       // printf("Lines of numbers.txt file are: %s", line);     
        numbers[i]=atoi(line);  /* convert string to double float*/
        i++;
    }
    totalNums = i;
    for (i=0 ; i<totalNums ; i++) {
        printf("\nThe number %d of %d is: %.0f", i+1, totalNums, numbers[i]);
        
    }
    fclose(file); 
    return 0;
}

the last column what i mean is last sort last element of each line
but to to store every element into array ?

Edited 5 Years Ago by guidely: n/a

double atof ( const char * str );

You need not (and probably should not) do that. Function 'atof' is already declared in the standard library 'stdlib.h' and besides you're not even using it:

numbers[i]=atoi(line);  /* convert string to double float*/

But that's what you should've done, because atoi converts the string to an 'int' type, not a 'double float'.
You should check for errors while opening a file stream, like this:

totalNums = i;
for (i=0 ; i<totalNums ; i++) {
printf("\nThe number %d of %d is: %.0f", i+1, totalNums, numbers[i]);
if((file = fopen("test.txt", "r"))==NULL)  /* open a text file for reading */
        exit(1);//couldn't open the requested file!

And have a good luck with whatever you're trying to do up there.

This article has been dead for over six months. Start a new discussion instead.