1

I have a file with 6.321.078 records, they are formed by couple of integers separated by a comma. My aim is to read line by line and save it inside a char array (so, strings). My trouble is , when I run sscanf() it doesn't work. I think that this is the problem but I'm not sure that is the only one. I know that the file contain INT, but I need to save every line such as string. What can I do and why does not it work? (There is an example of my file.csv below)

main.c:

int main() {
    FILE *fd;
    char *arr;
    arr = (char *)malloc(6321078);
    for (int k = 0; k < 6321078; k++) {
        arr[k] = calloc(20, sizeof(char));
    }
    char *r;
    int pos = 0;
    int n;
    fd = fopen("file.csv", "r");
    if (fd == NULL) {
       perror("Error");
       exit(1);
    }

    while (fgets(r, sizeof(r), fd) != NULL) {
        sscanf(r, "%s", arr[pos]);
        printf("%s", arr[pos]);
        pos++;
    }
}

Example of file.csv:

enter image description here

2
  • 1
    I really can't unravel what the code is supposed to do. arr[k] = calloc(20, sizeof(char)); that doesn't make sense as arr has not been allocated as an array of char * but rather an array of char. char *r; fgets(r,sizeof(r),fd) that is undefined behaviour as r is an unintialised pointer. And sizeof(r) will give just the size of a single pointer. Commented Nov 23, 2020 at 11:12
  • I want to create an array that contain strings with size 20. So how can I do this? @kaylum Commented Nov 23, 2020 at 11:18

1 Answer 1

1

A pointer to array of 20 could be used char (*arr)[20]
Then allocate memory for the number of records.
Use fgets to read directly from the file into each record.
When done, close the file and free the memory.

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

#define SIZE 6321078
#define LEN 20

int main ( void) {
    char (*arr)[LEN] = NULL;
    int pos = 0;
    FILE *fd = NULL;

    if ( NULL == ( fd = fopen("file.csv", "r"))) {
        perror("Error");
        exit ( EXIT_FAILURE);
    }

    if ( NULL == ( arr = calloc ( SIZE, sizeof *arr))) {
        fclose ( fd);
        fprintf ( stderr, "calloc problem\n");
        exit ( EXIT_FAILURE);
    }

    while ( pos < SIZE && fgets ( arr[pos], sizeof arr[pos], fd)) {
        printf ( "%s", arr[pos]);
        ++pos;
    }

    fclose ( fd);
    free ( arr);

    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.