I got some file-reading problems in my project, so I wrote following test codes.
I'm tring to read a file by ifstream.read()
,but anything has been read.
I've searched numerous related questions, but still can't figure out why my code doesn't work. please help.
#include <iostream>
#include <fstream>
int main() {
/*--------------- write file ----------------*/
std::ofstream ofs("testfile", std::ios::binary);
const char *content = "11223344";
ofs.write(content, sizeof content);
system("chmod 777 testfile");
/*--------------- read file ----------------*/
char arr[8] = {0};
const int length = sizeof arr / sizeof arr[0];
std::ifstream ifs("testfile", std::ios::binary);
std::cout << "good: " << ifs.good() << std::endl; // 1
ifs.seekg(0, ifs.end);
int file_size = ifs.tellg();
ifs.seekg(0, ifs.beg);
std::cout << "file_size: " << file_size << std::endl << std::endl; // 0
if (ifs) {
ifs.read(&arr[0], 2);
std::cout << "after read," << std::endl;
std::cout << "gcount: " << ifs.gcount() << std::endl; // 0
std::cout << "good: " << ifs.good() << std::endl; // 0
ifs.read(&arr[2], 2);
ifs.read(&arr[4], 2);
ifs.read(&arr[6], 2);
} else {
std::cout << "file not found" << std::endl;
}
for (int i = 0; i < length; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
}
The output is
good: 1
file_size: 0
after read,
gcount: 0
good: 0
0 0 0 0 0 0 0 0
Aucun commentaire:
Enregistrer un commentaire