C++ fread: Read Files Efficiently

In C++, you can read files by calling the standard library function fread. Here is a simple example that demonstrates how to use fread to read a file:

#include <iostream>
#include <cstdio>

int main() {
    FILE *fp = fopen("example.txt", "rb"); // 打开文件以二进制模式读取
    if (fp == NULL) {
        std::cout << "Error opening file" << std::endl;
        return 1;
    }

    char buffer[100]; // 用于存储读取的数据
    size_t bytesRead = fread(buffer, 1, 100, fp); // 从文件中读取最多100个字节的数据
    if (bytesRead > 0) {
        std::cout << "Read " << bytesRead << " bytes: " << buffer << std::endl;
    } else {
        std::cout << "Error reading file" << std::endl;
    }

    fclose(fp); // 关闭文件
    return 0;
}

In this example, the file named “example.txt” is first opened using the fopen function in binary mode (“rb”). Next, the fread function is used to read up to 100 bytes of data from the file and store it in a character array named “buffer”. Finally, the number of bytes read and the data read are printed, and the file is closed.

bannerAds