美文网首页
(四)C++篇-文件写入和读取

(四)C++篇-文件写入和读取

作者: GoodTekken | 来源:发表于2022-06-16 08:56 被阅读0次

保证在运行目录中存在text.txt文件,否则需要附加相对路径或绝对路径找到该文件。

测试代码如下:

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int main()
{
    fstream myfile;
    
    //(1) 二选一: Append the text at the end.
    myfile.open ("text.txt",ofstream::app);
    myfile << "Writing this to a file.\n";
    myfile << "Hi Tekken.\n";
    myfile.close();
    
    //(2) 二选一: Clean the text 
    myfile.open ("text.txt",ofstream::out);
    myfile << "Writing this to a file.\n";
    myfile << "Hi Tekken.\n";
    myfile.close();
       
    // 读取文件
    string line;
    myfile.open("text.txt");
    if (myfile.is_open())
    {
        while(getline (myfile,line))
    {
        cout << line << '\n';
    }
        myfile.close();
    }

    else cout << "Unable to open file\n"; 

    return 0;
}

运行结果:

tekken@tekken:~/C++WS$ ./a.out 
Writing this to a file.
Hi Tekken.

相关文章

  • (四)C++篇-文件写入和读取

    保证在运行目录中存在text.txt文件,否则需要附加相对路径或绝对路径找到该文件。 测试代码如下: 运行结果:

  • fs文件系统操作

    基础写入文件 简单写入文件 流式文件写入 简单文件读取 流式文件读取 流式文件拷贝(读取 + 写入) 复制文件 f...

  • php获取数据放入文件

    一、打开文件 二、写入文件 三、读取文件 四、关闭

  • python 文件操作

    fp=open("文件路径","方式") 文件读取 文件写入 文件关闭 文件读取写入方式

  • 文件操作

    读取和写入:文件有内容读取就是将文件中的内容读取到内存中。写入就是将内存中的内容写入到磁盘文件中。内存就相当于你的...

  • C++高级教程(文件和流)

    1.fstream 作用:文件读取流和向文件写入流。 三种数据类型: 要在 C++ 中进行文件处理,必须在 C++...

  • txt读写

    文件打开 读文件 读取字符串 按行读取整个文件 写文件 字符串写入txt 列表写入文件 双层列表写入文件 数组写入文件

  • nodeJS读取json文件并写入txt或redis中

    【1:读取json写入txt文件】json文件book.json js文件 【2:读取json写入redis文件/...

  • Advanced:DCloud{一、本地存储文件}

    写入文件 读取文件

  • fs

    读取文件 写入文件

网友评论

      本文标题:(四)C++篇-文件写入和读取

      本文链接:https://www.haomeiwen.com/subject/aegfvrtx.html