Can I open a .xls or .PDF file using the open() function in C++ with binary mode and read its contents? If not, how can I build an application program that can read the contents of files with such file formats (and maybe more)
问题:
回答1:
Yes, you can open any file in your filesystem as a binary file, and you can read it too (as long as your operating system allows the file to be opened based on file access rights, and no other application has got a lock on it, etc).
Next you'll probably ask "How do I interpret a PDF or XLS file?" and that's a whole other kettle of fish as they say here in England. Neither PDF, nor XLS files are straight forward to "understand". A PDF librar that I looked at recently contains several dozen files, and is several megabytes of source code. I've worked with XLS files in Python, and the code there was a few thousand lines of code.
回答2:
Simple reading would be:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
std::vector<char> readfile(std::string const& fname)
{
std::ifstream ifs(fname.c_str(), std::ios::binary);
std::istreambuf_iterator<char> f(ifs.rdbuf()), l;
std::vector<char> bytes;
std::copy(f, l, std::back_inserter(bytes));
return bytes;
}
int main()
{
auto bytes = readfile("my.pdf");
}
回答3:
The argument mode points to a string beginning with one of the following sequences (Additional characters may follow these sequences.):
``r'' Open text file for reading. The stream is positioned at the beginning of the file.
``r+'' Open for reading and writing. The stream is positioned at the beginning of the file.
``w'' Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
``w+'' Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.
``a+'' Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subse- quent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.