0

I have to read the contents of a file, and store them in a char* array. I have the following, but when I output my char* array I don't get the full output of the file I read in. Am I incorrectly calculating the file size of my output array?

Note: I must use POSIX calls to read the contents of the file.

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

Contents of test.txt are This is a string of sample text

But this is my output when running:

file size: 34
This isfinished
yambo
  • 1,388
  • 1
  • 15
  • 34

0 Answers0