문제
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 구현이 있습니다.
다른 팁
당신은 ifstream
단지 읽고 싶다면( ofstream
글을 쓰거나, fstream
모두).
텍스트 모드에서 파일을 열려면 다음을 수행하십시오.
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;
int main () {
ofstream file;
file.open ("codebind.txt");
file << "Please writr this text to a file.\n this text is written using C++\n";
file.close();
return 0;
}
#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......
}
다음 단계를 따르세요.
- File 클래스에 액세스하려면 헤더 파일이나 네임스페이스를 포함합니다.
- IDE 플랫폼 (예 : CFILE, QFILE, FSTREAM)에 따라 파일 클래스 객체를 만듭니다.
- 이제 모든 파일을 열고/읽고/닫고/getline 또는 다른 클래스 메소드를 쉽게 찾을 수 있습니다.
CFile/QFile/ifstream m_file; m_file.Open(path,Other parameter/mood to open file);
파일을 읽으려면 데이터를 저장할 버퍼나 문자열을 만들어야 하며 해당 변수를 read() 메서드에 전달할 수 있습니다.
**#include<fstream> //to use file
#include<string> //to use getline
using namespace std;
int main(){
ifstream file;
string str;
file.open("path the file" , ios::binary | ios::in);
while(true){
getline(file , str);
if(file.fail())
break;
cout<<str;
}
}**
#include <fstream>
ifstream infile;
infile.open(**file path**);
while(!infile.eof())
{
getline(infile,data);
}
infile.close();
fstream은 훌륭하지만 조금 더 자세히 설명하겠습니다. 라이.
전형적인 예의 문제점은 강제로 파일을 스스로 닫아야 한다는 것입니다. 즉, 아키텍처를 이러한 요구에 맞게 조정해야 한다는 의미입니다.RAII는 C++의 자동 소멸자 호출을 사용하여 파일을 닫습니다.
업데이트:std::fstream은 이미 RAII를 구현한 것으로 보이므로 아래 코드는 쓸모가 없습니다.나는 후손을 위해 그리고 RAII의 예를 위해 여기에 보관할 것입니다.
class FileOpener
{
public:
FileOpener(std::fstream& file, const char* fileName): m_file(file)
{
m_file.open(fileName);
}
~FileOpeneer()
{
file.close();
}
private:
std::fstream& m_file;
};
이제 다음과 같이 코드에서 이 클래스를 사용할 수 있습니다.
int nsize = 10;
char *somedata;
ifstream myfile;
FileOpener opener(myfile, "<path to file>");
myfile.read(somedata,nsize);
// myfile is closed automatically when opener destructor is called
RAII의 작동 방식을 배우면 두통과 주요 메모리 관리 버그를 줄일 수 있습니다.