C++ 你如何在C++中打开一个文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:12:56  来源:igfitidea点击:

How do you open a file in C++?

c++fileio

提问by andrewrk

I want to open a file for reading, the C++ way. I need to be able to do it for:

我想打开一个文件进行阅读,C++ 方式。我需要能够做到:

  • text files, which would involve some sort of read line function.

  • binary files, which would provide a way to read raw data into a char*buffer.

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

  • 二进制文件,这将提供一种将原始数据读入char*缓冲区的方法。

采纳答案by DannySmurf

There are three ways to do this, depending on your needs. You could use the old-school C way and call fopen/fread/fclose, or you could use the C++ fstream facilities (ifstream/ofstream), or if you're using MFC, use the CFile class, which provides functions to accomplish actual file operations.

有三种方法可以做到这一点,具体取决于您的需要。您可以使用老式的 C 方式并调用 fopen/fread/fclose,或者您可以使用 C++ fstream 工具(ifstream/ofstream),或者如果您使用的是 MFC,请使用 CFile 类,它提供了完成实际操作的函数文件操作。

All of these are suitable for both text and binary, though none have a specific readline functionality. What you'd most likely do instead in that case is use the fstream classes (fstream.h) and use the stream operators (<< and >>) or the read function to read/write blocks of text:

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

int nsize = 10;
char *somedata;
ifstream myfile;
myfile.open("<path to file>");
myfile.read(somedata,nsize);
myfile.close();

Note that, if you're using Visual Studio 2005 or higher, traditional fstream may not be available (there's a new Microsoft implementation, which is slightly different, but accomplishes the same thing).

请注意,如果您使用的是 Visual Studio 2005 或更高版本,则传统的 fstream 可能不可用(有一个新的 Microsoft 实现,它略有不同,但完成相同的事情)。

回答by Derek Park

You need to use an ifstreamif you just want to read (use an ofstreamto write, or an fstreamfor both).

ifstream如果您只想阅读,则需要使用 an (使用 anofstream写入,或fstream两者兼用an )。

To open a file in text mode, do the following:

要以文本模式打开文件,请执行以下操作:

ifstream in("filename.ext", ios_base::in); // the in flag is optional

To open a file in binary mode, you just need to add the "binary" flag.

要以二进制模式打开文件,您只需要添加“二进制”标志。

ifstream in2("filename2.ext", ios_base::in | ios_base::binary ); 

Use the ifstream.read()function to read a block of characters (in binary or text mode). Use the getline()function (it's global) to read an entire line.

使用该ifstream.read()函数读取一个字符块(以二进制或文本模式)。使用getline()函数(它是全局的)读取整行。

回答by Ziezi

To open and read a text file line per line, you could use the following:

要打开并读取每行文本文件行,您可以使用以下命令:

// 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);
}

To open and read a binary file you need to explicitly declare the reading format in your input stream to be binary, and read memory that has no explicit interpretation using stream member function read():

要打开和读取二进制文件,您需要将输入流中的读取格式显式声明为二进制,并使用流成员函数读取没有显式解释的内存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);

When doing this you'll need to #includethe header : <iostream>

这样做时,您需要#include标题:<iostream>

回答by Nardine Nabil

#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;
}

回答by Kartik Maheshwari

Follow the steps,

按照步骤,

  1. Include Header files or name space to access File class.
  2. Make File class object Depending on your IDE platform ( i.e, CFile,QFile,fstream).
  3. Now you can easily find that class methods to open/read/close/getline or else of any file.
  1. 包含头文件或名称空间以访问 File 类。
  2. 根据您的 IDE 平台(即 CFile、QFile、fstream)生成 File 类对象。
  3. 现在您可以轻松找到打开/读取/关闭/getline 或其他任何文件的类方法。
CFile/QFile/ifstream m_file;
m_file.Open(path,Other parameter/mood to open file);
CFile/QFile/ifstream m_file;
m_file.Open(path,Other parameter/mood to open file);

For reading file you have to make buffer or string to save data and you can pass that variable in read() method.

要读取文件,您必须创建缓冲区或字符串来保存数据,您可以在 read() 方法中传递该变量。

回答by Karim Salah

**#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;
}
}**

回答by J.p.

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

回答by Maria Emil

#include <fstream>

ifstream infile;
infile.open(**file path**);
while(!infile.eof())
{
   getline(infile,data);
}
infile.close();

回答by Vincent Robert

fstream are great but I will go a little deeper and tell you about RAII.

fstream 很棒,但我会更深入地告诉您有关RAII 的信息

The problem with a classic example is that you are forced to close the file by yourself, meaning that you will have to bend your architecture to this need. RAII makes use of the automatic destructor call in C++ to close the file for you.

一个经典示例的问题是您被迫自己关闭文件,这意味着您将不得不根据这种需要调整您的架构。RAII 利用 C++ 中的自动析构函数调用为您关闭文件。

Update: seems that std::fstream already implements RAII so the code below is useless. I'll keep it here for posterity and as an example of RAII.

更新:似乎 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;
};

You can now use this class in your code like this:

你现在可以在你的代码中使用这个类,如下所示:

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

Learning how RAII works can save you some headaches and some major memory management bugs.

了解 RAII 的工作原理可以为您省去一些麻烦和一些主要的内存管理错误。