C++读写文件数据块

一 复制文件

1 代码

// Copy a file
#include       // std::ifstream, std::ofstream

int main() {
    std::ifstream infile("myfile.txt", std::ifstream::binary);
    std::ofstream outfile("new.txt", std::ofstream::binary);

      // get size of file
    infile.seekg(0, infile.end);
    long size = infile.tellg();
    infile.seekg(0);

      // allocate memory for file content
    char* buffer = new char[size];

      // read content of infile
    infile.read(buffer, size);

      // write to outfile
    outfile.write(buffer, size);

      // release dynamically-allocated memory
    delete[] buffer;

    outfile.close();
    infile.close();
    return 0;
}

2 运行

[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
[root@localhost test]# cat new.txt
cakin
33

二 读取文件到内存

1 代码

// read a file into memory
#include      // std::cout
#include       // std::ifstream

int main() {

    std::ifstream is("myfile.txt", std::ifstream::binary);
    if (is) {
      // get length of file:
        is.seekg(0, is.end);
        int length = is.tellg();
        is.seekg(0, is.beg);

        char * buffer = new char[length];

        std::cout << "Reading " << length << " characters... ";
        // read data as a block:
        is.read(buffer, length);

        if (is)
            std::cout << "all characters read successfully.";
        else
            std::cout << "error: only " << is.gcount() << " could be read";
        is.close();

            // ...buffer contains the entire file...

        delete[] buffer;
    }
}

2 运行

[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
Reading 9 characters... all characters read successfully.

 

你可能感兴趣的:(C++)