简体   繁体   中英

Reading from file and store it to string with unknown length in c

I'm trying to read text from a file and store it into a string so that I can then encrypt and decrypt it using openssl. How can I do this?

You could use dynamic memory. My "skeleton" code for reading any type of file is this:

// Assumes: the file @ file name is a text file; ASCII or UTF-8 (no BOM)
void readwholefile(char *filename)
{
    FILE *fp;
    char *buffer = NULL;
    size_t i, len;

    fp = fopen(filename, "rb");
    fseek(fp, 0, SEEK_END);
    len = ftell(fp);
    rewind(fp);
    buffer = malloc(len + 1);
    if (NULL == buffer)
    {
        // Handle malloc failure & exit
        exit(-1);
    }

    fread(buffer, 1, len, fp);
    fclose(fp);
    buffer[len] = '\0';
    // buffer now contains the content of your file; do what you want with it

    free(buffer);
    buffer = NULL;
}

If you are using a POSIX system, you can use getline :

char *line = nullptr;
size_t line_size = 0
ssize_t len = getline(&line, &line_size, fp);

This will read until a newline and malloc enough space for the resulting line. You can use getdelim to read up to some delimiter other than a newline.

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