John Walter
John Walter

Reputation: 141

How to read data from a file in C?

I have a file containing the information

0001:Jack:Jeremy:6:38.0
0002:Mat:Steve:1:44.5
0003:Jessy:Rans:10:50.0
0004:Van Red:Jimmy:3:25.75
0005:Peter:John:8:42.25
0006:Mat:Jeff:3:62.0

I want to get data from this file so each part of this string will have each value. For example, double num will be 3; char firstn[20] will be 'Jack', char lastn[20] will be 'Jeremy', int t will be 6, and double hour will be 38.0, and so on.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    FILE *read, *write;
    int i, group;
    double hours, num;
    char lastn[20],
         firstn[20];

    read = fopen("people.txt", "r");
    if (read == NULL) {
        printf("Error, Can not open the file\n");
        exit(0);
    }
    write = fopen("people.dat", "w");
    for (i=0; i<6; i++) {
        fscanf(read, "%lf:%s:%s:%d:%lf", &num, lastn, firstn, &group, &hours);
        fprintf(write, "Number: %lf Fname: %s Lastn: %s Group: %d Hours: %.1lf\n", num, lastn, firstn, group, hours);
    }
    fclose(read);
    fclose(write);

    return 0;
}

When I am trying to do so, my string lastn takes all the information until the end of line.

How can I specify so string firstn will take only characters until : and then string lastn will take only Jeremy, and group will take only 6, and so on?

Upvotes: 0

Views: 626

Answers (3)

Jonathan Leffler
Jonathan Leffler

Reputation: 753455

You can modify your fscanf() format string.

if (fscanf(read, "%lf:%19[^:]:%19[^:]:%d:%lf", &num, lastn, firstn, &group, &hours) != 5)
    ...the read failed...

The notation %19[^:] means 'read up to 19 non-colon characters' into the string, followed by a null. Note that the variables lastn and firstn are char[20]. Note that the conversion is checked; if you get an answer other than 5, something went wrong. You might consider scanning the rest of the line up to a newline after the fscanf() call:

int c;
while ((c = getc(read)) != EOF && c != '\n')
    ;

You should also check that you succeeded in opening the output file.

Upvotes: 2

Mark Tolonen
Mark Tolonen

Reputation: 177406

Try:

fscanf(read, "%lf:%[^:]:%[^:]:%d:%lf", &num, lastn, firstn, &group, &hours);

%[^:] means read a a string not including a colon. See scanf.

Upvotes: 1

P.P
P.P

Reputation: 121347

Use fgets() to read line and then tokenize it using strtok()

char line[100];
char *p;

fgets(line);
p = strtok(line, ":");

Now you can store tokens into variables as you like.

Upvotes: 1

Related Questions