C++ fread Loop File Read Guide
You can use the fread function in C++ to loop through reading data from a file. Here is an example code snippet demonstrating how to use the fread function to loop through reading a file.
#include <iostream>
#include <cstdio>
int main() {
FILE *file = fopen("example.txt", "rb"); // 以二进制只读模式打开文件
if (file == NULL) {
std::cerr << "Error opening file" << std::endl;
return 1;
}
const int bufferSize = 1024;
char buffer[bufferSize];
size_t bytesRead = 0;
// 循环读取文件直到读取到文件末尾
while ((bytesRead = fread(buffer, 1, bufferSize, file)) > 0) {
// 处理读取到的数据,这里简单打印到控制台
for (size_t i = 0; i < bytesRead; i++) {
std::cout << buffer[i];
}
}
fclose(file);
return 0;
}
In this example, we start by opening a file named example.txt using the fopen function. Then, we use the fread function to read the data in the file within a loop, reading data of size bufferSize each time and outputting it to the console. The loop ends when the fread function returns 0, indicating that the end of the file has been reached.
Finally, close the file stream using the fclose function.