簡體   English   中英

從文件中讀取並將其存儲到 c 中長度未知的字符串中

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

我正在嘗試從文件中讀取文本並將其存儲到一個字符串中,以便我可以使用 openssl 對其進行加密和解密。 我怎樣才能做到這一點?

您可以使用動態內存。 我用於讀取任何類型文件的“骨架”代碼是這樣的:

// 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;
}

如果您使用的是 POSIX 系統,則可以使用getline

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

這將一直讀到換行符和 malloc 足夠的空間用於結果行。 您可以使用getdelim讀取除換行符以外的某些分隔符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM