问题描述
这是我在堆栈溢出时遇到的第一个问题,因此,如果我搞砸了任何东西,请多多怜悯(大声笑) 编码语言:C ++ IDE:代码::块 编译器:GNU GCC 操作系统:Windows
让我澄清一下: 这是我的代码:
#include <iostream>
#include <fstream>
int main() {
std::fstream fileObject;
std::string line;
fileObject.open("randomFile.txt");
fileObject << "Random text\n kjshjdfgxhkjlwkdgxsdegysh";
while (getline(fileObject,line) ) {
std::cout << line << "\n";
}
fileObject.close();
}
这没有任何错误,但是当我检查项目文件时,文件randomFile不存在,控制台屏幕上也没有出现任何文本。 但是,此代码确实有效:
#include <iostream>
#include <fstream>
int main() {
std::ofstream fileObject;
fileObject.open("randomFile.txt");
fileObject << "Random text\n kjshjdfgxhkjlwkdgxsdegysh";
fileObject.close();
}
它将创建文件并插入指定的文本... 我还有一个次要问题:如果我尝试使用相同的名称制作一个ifstream和ofstream对象,它将显示为错误,但是我无法弄清楚如何做到这一点,这样我既可以写文件也可以从中读取它使用相同的代码...
解决方法
您需要阅读文档,不能通过猜测工作来编写C ++。这些选项使您可以打开文件以同时进行读写,但要注意以下几点
// error if the file does not exist
std::fstream fileObject("randomFile.txt");
或(同一件事)
// error if the file does not exist
std::fstream fileObject("randomFile.txt",std::ios_base::in|std::ios_base::out);
或
// destroys contents if the file exists,but creates file if it does not
std::fstream fileObject("randomFile.txt",std::ios_base::in|std::ios_base::out|std::ios_base::trunc);
如果这些选项都不是您想要的,那么您将必须在打开文件之前检查文件是否存在。
参考here。