首页 > 解决方案 > 将文本文件的内容存储在 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

标签: c++arrayssizeposixchar-pointer

解决方案


推荐阅读