c++ - 将文本文件的内容存储在 C++ 中的 char* 数组中
问题描述
我必须读取文件的内容,并将它们存储在 char* 数组中。我有以下内容,但是当我输出我的 char* 数组时,我没有得到我读入的文件的完整输出。我是否错误地计算了输出数组的文件大小?
注意:我必须使用 POSIX 调用来读取文件的内容。
#include "iostream"
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
using namespace std;
int main() {
const char* name = "test.txt";
int fd = open(name, O_RDONLY);
off_t length = lseek(fd, 0, SEEK_END);
cout << "file size: " << length << endl;
char* array = new char[length];
lseek(fd, 0, SEEK_SET); // resets position to 0
read(fd, array, sizeof(array)-1);
cout << array << "finished" << endl;
close(fd);
delete[] array;
return 0;
}
test.txt 的内容是This is a string of sample text
但这是我运行时的输出:
file size: 34
This isfinished
解决方案
推荐阅读
- r - R - 过滤器给出错误“参数暗示不同的行数:0、1”
- python - 我做了一个非常简单的 Pygame Zero 游戏,但是我的 Actor 图像和 screen.clear() 不起作用。你能帮我解决这个问题吗?
- reactjs - 盖茨比图像 Chrome 在 Windows 10 上闪烁
- sql - Google Sheet 获取一个主值的所有半值的总和
- mysql - 无法识别涉及我的两个表的正确查询
- javascript - jQuery记住列表中的toggleClass状态
- python-3.x - 将 pandas 数据帧写入 Azure Blob - Python sdk
- php - Codeigniter 文件夹结构中的错误...您的应用程序文件夹路径似乎设置不正确
- macos - macOS 11.4 Beta 阻止网站在明显有效的证书上显示无效证书
- dataset - 如何减去SPSS中相同变量列中的值?