您在C++中执行以下与文件相关的操作吗?

Was*_*f K 2 c++ file-io

如何在C++中执行以下操作?

  1. 打开文件
  2. 关闭文件
  3. 阅读文件
  4. 写文件

Mar*_*ork 12

#include <fstream>
int main()
{
    std::ifstream    inputFile("MyFileName")  // Opens a File.

    int  x;
    inputFile >> x; // Reads an integer from a file.

    std::string word;
    inputFile >> word; // Reads a space separated word from a file.

    double y;
    inputFile >> y; // Reads a floating point number from the file.

    // etc..
 } // File AutoMagically closed by going out of scope.
Run Code Online (Sandbox Code Playgroud)

写作

#include <fstream>
int main()
{
    std::ofstream    inputFile("MyFileName")  // Opens a File.

    int  x = 5;
    inputFile << x << " "; // Writes an integer to a file then a space.
    inputFile << 5 << " "; // Same Again.

    std::string word("This is a line");
    inputFile << word << "\n"; // Writes a string to a file followed by a newline
                               // Notice the difference between reading and
                               // writing a string.
    inputFile << "Write a string constant to a file\n";

    double y = 15.4;
    inputFile << y << ":"; // Writes a floating point number 
                           // to the file followed by ":".

    // etc..
 } // File AutoMagically closed by going out of scope.
Run Code Online (Sandbox Code Playgroud)


Joh*_*itb 6

一次全部

{ 
    std::ifstream in("foo.txt"); /* opens for reading */
    std::ofstream out("bar.txt"); /* opens for writing */
    out << in.rdbuf(); /* streams in into out. writing and reading */
} /* closes automatically */
Run Code Online (Sandbox Code Playgroud)