top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to extract data from txt file using C?

0 votes
624 views

Example of txt file:

Voltage (V),Current (I),Power (W)
50,2,100,
51,2,102,
52,2,104,

How can I display only the column of Voltage and Power?

posted Jan 13, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Here is code for that (tested)

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

int main()
{
    FILE *fp = NULL;
    char *token, dlim[2] = ",", buff[50];
    int i = 0;

    fp = fopen("file.txt", "r+");
    if (fp == NULL)
        return 0;  //Return  if unable to open the file.

    printf("Only going to print Voltage and Power coloum values.\n");
    while (fgets(buff, 50, fp) != NULL) {
        if (i == 0) {
            i = 1;
            continue; //to skip the first line.
        }

        /* get the first token */
        token = strtok(buff, dlim);

        while (token != NULL ) {
            printf("%s   ", token);
            token = strtok(NULL, dlim);
            token = strtok(NULL, dlim); //for skiping the second colom of each line. i.e Current vaule.
        }
        printf("\n");
    }
    fclose(fp);
    return 0;
}
answer Jan 13, 2015 by Arshad Khan
...