Search code examples
creadfile

how to read a file and save content in a string? (in C language without crash or core dump error)


I wrote a code to read a file. Read the default file or another file and store the content file in a string. I don't know where I went wrong! When I run it, sometimes it's ok, but sometimes I get a Core Dump error!

This is my code:

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

#define BUFFER_SIZE 1024
#define EXAMPLE_FILE "programing_languages.example"
#define EXAMPLE_FILE_SIZE strlen(EXAMPLE_FILE)+1


int read_file(char *buffer, char *file_name)
{
    FILE *file;

    file = fopen(file_name, "r");

    if (file == NULL)
    {
        printf("Warning!!!");
        return 1;
    }

    fread(buffer, sizeof(char), BUFFER_SIZE, file);

    fclose(file);

    return 0;
}


int main(int argc, char *argv[])
{   
    int opt;
    int file_name_customized = 0;
    char *file_name;

    while ((opt = getopt(argc, argv, "f:")) != -1) {
        switch (opt) {
            case 'f':
                snprintf(file_name, strlen(argv[2])+1, "%s", argv[2]);
                file_name_customized = 1;
                break;
            default:
                snprintf(file_name, EXAMPLE_FILE_SIZE, EXAMPLE_FILE);
        }
    }

    if (!file_name_customized)
    {
        snprintf(file_name, EXAMPLE_FILE_SIZE, EXAMPLE_FILE);
    }

    char buffer[BUFFER_SIZE] = {"\0"};

    if (read_file(buffer, EXAMPLE_FILE) == 1)
    {
        printf("Got Error To Open %s File!\n", file_name);
        return errno;
    }

    printf("%s\n", buffer);

}

I want to read a file and save it to a string. (in C language)


Solution

  • how to read a file and save content in a string?

    1. Open the file. Check for errors.
    2. Read entire file via fread() with a good size buffer, say 4K and sum the lengths returned.
    3. Continue step 2 until error or nothing read.
    4. Allocate sum + 1. Check for allocation success.
    5. Reread entire file with 1 fread() into the allocated buffer. Note the length returned.
    6. Close the file.
    7. Append a null character.
    8. If length is as expected, success, else failure.
    9. Return the allocated pointer or NULL on failure.