c++读取文件到string
时间: 2023-09-02 09:12:34 浏览: 147
要将C语言读取文件到字符串,可以使用以下代码:
```c
#include <stdio.h>
#include <stdlib.h>
char* readFileIntoString(const char* filename) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("无法打开文件\n");
return NULL;
}
// 获取文件大小
fseek(file, 0, SEEK_END);
long fileSize = ftell(file);
fseek(file, 0, SEEK_SET);
// 分配内存存储文件内容
char* buffer = (char*)malloc(fileSize + 1);
if (buffer == NULL) {
fclose(file);
printf("内存分配失败\n");
return NULL;
}
// 读取文件内容
size_t bytesRead = fread(buffer, 1, fileSize, file);
if (bytesRead < fileSize) {
fclose(file);
free(buffer);
printf("读取文件时发生错误\n");
return NULL;
}
// 添加字符串结束符
buffer = '\0';
fclose(file);
return buffer;
}
int main() {
const char* filename = "a.txt";
char* fileContent = readFileIntoString(filename);
if (fileContent != NULL) {
// 打印文件内容
printf("%s\n", fileContent);
// 释放内存
free(fileContent);
}
return 0;
}
```
上述代码定义了一个函数`readFileIntoString`,它接受一个文件名作为参数,然后打开文件并读取文件内容到一个动态分配的字符串中。最后,它返回这个字符串。在主函数中,我们可以调用`readFileIntoString`函数来读取文件并将其内容打印出来。请确保文件存在并且有足够的权限来读取它。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [C++ 读文件 将文件内容读入到字符串string中的方法](https://download.csdn.net/download/weixin_38751016/13996677)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [C++ 读文件 将文件内容读入到字符串string中](https://blog.csdn.net/my_xxh/article/details/51278440)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [老歪用Qt C++写的读取SEGY和SEGD格式的地震数据源码,支持波形显示和变密度显示 在Qt5.12版本上编译通过](https://download.csdn.net/download/Idealtracy/88244376)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文