简体   繁体   English

从文件中读取并将其存储到 c 中长度未知的字符串中

[英]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.我正在尝试从文件中读取文本并将其存储到一个字符串中,以便我可以使用 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 :如果您使用的是 POSIX 系统,则可以使用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.这将一直读到换行符和 malloc 足够的空间用于结果行。 You can use getdelim to read up to some delimiter other than a newline.您可以使用getdelim读取除换行符以外的某些分隔符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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