fstream没有在文件中写入任何内容
fstream is not writing anything on the file
我试图将一些内容写入文本文件,但它甚至无法创建文件。如果你能帮我做这件事,我将不胜感激。谢谢
#include <fstream>
#include <iostream>
int main(){
std::ofstream file;
file.open("path/to/file");
//write something to file
file << "test";
//printing to screen
std::cout << file.rdbuf();
//closing file
file.close();
return 0;
}
下面一行是罪魁祸首:
std::cout << file.rdbuf();
不能使用rdbuf
输出仅为写入操作打开的文件。
删除该行,您的文件将被正确写入。
如果你想在写完文件后阅读它:
解决方案1:使用fstream
:打开file
进行读写操作
std::fstream file("path/to/file", std::ios::in | std::ios::out);
// ... write to file
file.seekg(0); // set read position to beginning of file
std::cout << file.rdbuf();
解决方案2:创建一个新的std::ifstream
以从文件中读取:
// ... write to file
file.close(); // call `close` to make sure all input is written to file
std::ifstream inputFile("path/to/file");
std::cout << inputFile.rdbuf();
salesFile.open("C:\Users\Tebsan\Desktop\Coding\c++\re\salesFile.txt"); // ...try to open existing file
if( !salesFile.is_open() ) // ...else, create new file...
salesFile.open("C:\Users\Tebsan\Desktop\Coding\c++\re\salesFile.txt", ios_base::in | ios_base::out | ios_base::trunc);
您必须使用的显式openmode参数调用fstream::open
ios_base::in | ios_base::out | ios_base::trunc
否则,由于ENOENT,打开将失败。
感谢您的帮助!!!我从中学到了新东西。有趣的是,问题是文件的名称,显然名称太长了,对于包含文件流的新文件,我只是在名称的末尾添加了流,所以编译器一直运行第一个文件(没有文件流)。。。
相关文章:
- 是否有任何内置的哈希图函数来处理 c++ 中的值输入?
- 是否有任何内置函数可以检查给定的两个数字在给定整数数组中的顺序是否相同?
- Visual Studio 停止识别任何包含文件
- C++ 中是否有任何内置阶乘函数?
- 是否有任何内置函数可以告诉编译器分支是否可预测
- 打开任何文本文件
- 在新的Visual Studio项目中包含任何Eigen 3.3.1文件将无法编译
- 似乎没有任何读取文件的方法可以工作,所有方法都不返回任何东西-C++
- 我需要在C /C#中使用图形.我可以使用任何内置的C /C#库
- 是否有任何内置类可以处理C 中的大整数值
- 在未包含在任何其他文件中的文件中使用 extern 变量是否有任何可能的用途
- 是否可以在不使用任何头文件的情况下在C++中执行I/O操作
- 在 C++ 中将编辑过的内文件保存到输出文件时出现问题
- c ++中是否有任何内置功能可以在计划的时间运行任务
- 是否有任何内置的 UTF 在 c++ 在窗口中
- 尝试从 c 执行任何二进制文件
- 使用模板类时,似乎无法包含除 main 以外的任何 cpp 文件.cpp
- CMake表示,它已经编写了构建文件,但没有找到任何构建文件
- 在VC++2010中执行任何内置的ARRAY函数
- C++:如何在不使用任何内置函数的情况下将字符串转换为整数