简体   繁体   中英

How to read in txt file in CSV format and save into array in C

I am new to C and I need to read in a .txt file where there are 3 fields in each line separated by a comma, and I need to save it into an array. I am wondering how to do this? Here is an example file:

0, "test", 100
1, "hi", 2
2, "goodbye", 0

So I am wondering how to read the file line by line and to store each element into an array. I have started by defining a struct:

typedef struct data {
  int col1;
  char *col2;
  int col3;
} data_t;

Could anyone help me out to get started with the file opening?

For file opening there is a standard library (include stdio.h) function named fopen . It has the following declaration:

FILE *fopen(const char *filename, const char *mode);

As you can see it expects you to provide a pointer to const char for both filename and mode (read/write/read+write). It will return a pointer to a FILE so inside the function where you intend to work with it you'd have to declare one like this:

FILE *my_file;

It's also a good idea to initialize it to NULL so that you can check for errors when using fopen .

In your main function (purely for reading):

FILE *my_file = NULL;
my_file = fopen("filename.txt", "r");

And check for the returned pointer:

if (my_file == NULL)
    //error message etc.

The SQLite shell has an .import command that reads CSV. It is worthy of study. You can find it here ; search for CSVReader to see how it's coded.

simply sample(check omit)

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

#define NUMOFDATA 10

typedef struct data {
    int col1;
    char *col2;
    int col3;
} data_t;

int main(){
    data_t data_array[NUMOFDATA];
    int data_count = 0;
    char line[128];
    FILE *fp;
    fp=fopen("data.txt", "r");
    while(fgets(line, sizeof(line), fp)){
        int col1, col3;
        char col2[64];
        if(sscanf(line, "%d, %63[^,], %d", &col1, col2, &col3)==3){
            char *cl2p = col2;
            data_array[data_count].col1 = col1;
            data_array[data_count].col3 = col3;
            if(col2[0] == '"'){
                char *p = strchr(&col2[1], '"');
                if(p)
                    *p = '\0';
                cl2p = &col2[1];
            }
            data_array[data_count].col2 = strdup(cl2p);
//printf("%d, \"%s\", %d\n",data_array[data_count].col1,data_array[data_count].col2,data_array[data_count].col3);
            if(++data_count == NUMOFDATA)break;
        }
    }
    fclose(fp);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM