c++ - read - fstream write
你如何用C++打開一個文件? (4)
我想打開一個文件閱讀,C ++的方式。 我需要能夠做到這一點:
文本文件,這將涉及某種讀線功能。
二進製文件,這將提供一種方式來讀取原始數據到
char*
緩衝區。
有三種方法可以做到這一點,這取決於您的需求。 你可以使用老派的C方法並調用fopen / fread / fclose,或者你可以使用C ++ fstream工具(ifstream / ofstream),或者如果你使用的是MFC,使用CFile類,它提供函數來實現實際文件操作。
所有這些都適用於文本和二進制,但沒有一個具有特定的readline功能。 在這種情況下,你最有可能做的是使用fstream類(fstream.h),並使用流操作符(<<和>>)或讀函數來讀/寫文本塊:
int nsize = 10;
char *somedata;
ifstream myfile;
myfile.open("<path to file>");
myfile.read(somedata,nsize);
myfile.close();
請注意,如果您使用的是Visual Studio 2005或更高版本,傳統的fstream可能無法使用(有一個新的Microsoft實現,稍有不同,但完成同樣的事情)。
如果你只是想讀(使用ofstream
寫,或兩者都是fstream
),你需要使用ifstream
。
要以文本模式打開文件,請執行以下操作:
ifstream in("filename.ext", ios_base::in); // the in flag is optional
要以二進制模式打開文件,只需添加“二進制”標誌。
ifstream in2("filename2.ext", ios_base::in | ios_base::binary );
使用ifstream.read()
函數讀取一個字符塊(二進製或文本模式)。 使用getline()
函數(它是全局的)來讀取整行。
要打開並讀取每行的文本文件行,可以使用以下命令:
// define your file name
string file_name = "data.txt";
// attach an input stream to the wanted file
ifstream input_stream(file_name);
// check stream status
if (!input_stream) cerr << "Can't open input file!";
// file contents
vector<string> text;
// one line
string line;
// extract all the text from the input file
while (getline(input_stream, line)) {
// store each line in the vector
text.push_back(line);
}
要打開和讀取二進製文件,您需要顯式聲明輸入流中的讀取格式為二進製文件,並使用流成員函數read()
沒有顯式解釋的內存:
// define your file name
string file_name = "binary_data.bin";
// attach an input stream to the wanted file
ifstream input_stream(file_name, ios::binary);
// check stream status
if (!input_stream) cerr << "Can't open input file!";
// use function that explicitly specifies the amount of block memory read
int memory_size = 10;
// allocate 10 bytes of memory on heap
char* dynamic_buffer = new char[memory_size];
// read 10 bytes and store in dynamic_buffer
file_name.read(dynamic_buffer, memory_size);
當你這樣做時,你需要#include
標頭: <iostream>
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
ifstream in_stream; // fstream command to initiate "in_stream" as a command.
char filename[31]; // variable for "filename".
cout << "Enter file name to open :: "; // asks user for input for "filename".
cin.getline(filename, 30); // this gets the line from input for "filename".
in_stream.open(filename); // this in_stream (fstream) the "filename" to open.
if (in_stream.fail())
{
cout << "Could not open file to read.""\n"; // if the open file fails.
return;
}
//.....the rest of the text goes beneath......
}