我想以 C++ 方式打开一个文件进行读取。我需要能够做到这一点:

  • 文本文件,这将涉及某种读取行功能。

  • 二进制文件,这将提供一种将原始数据读取到 char* 缓冲。

有帮助吗?

解决方案

根据您的需要,可以通过三种方法来执行此操作。您可以使用老式的 C 方式并调用 fopen/fread/fclose,或者您可以使用 C++ fstream 工具 (ifstream/ofstream),或者如果您使用 MFC,请使用 CFile 类,它提供了完成实际操作的函数。文件操作。

所有这些都适用于文本和二进制,尽管没有一个具有特定的读取行功能。在这种情况下,您最有可能做的是使用 fstream 类 (fstream.h) 并使用流运算符(<< 和 >>)或 read 函数来读取/写入文本块:

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......
}

按照步骤,

  1. 包含头文件或名称空间来访问 File 类。
  2. 根据您的IDE平台(即CFILE,QFILE,FSTREAM)制作文件类对象。
  3. 现在您可以轻松找到打开/读取/关闭/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.

经典示例的问题是您被迫自己关闭文件,这意味着您必须调整架构以满足此需求。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 的工作原理可以帮助您避免一些头痛和一些主要的内存管理错误。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top