![](/img/trans.png)
[英]Dynamically allocated unknown length string reading from file (it has to be protected from reading numbers from the file) in 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.