C++ 如果文件存在,则使用它,如果不存在,则创建它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23967697/
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
If file exist, work with it, if no, create it
提问by Kryston
fstream datoteka;
datoteka.open("Informacije.txt", fstream::in | fstream::out | fstream::app);
if(!datoteka.is_open()){
ifstream datoteka("Informacije.txt")
datoteka.open("my_file.txt", fstream::in | fstream::out | fstream::app);
}/*I'm writing IN the file outside of that if statement.
So what it should do is create a file if it was not created before, and if it is created write into that file.
所以它应该做的是创建一个文件,如果它之前没有创建,如果它被创建,则写入该文件。
Hello there, so what I wanted from my program is that it check if the file already exists, sothe program open if it does and I can write in it, if the file is not opened(have not been created before) the program create it. So the problem is when I create a .csv file, and finish writing and I wanted to check if the written is really there, the file cannot be opened. In .txt file, everything is blank.
你好,所以我想从我的程序中检查文件是否已经存在,如果它存在,那么程序打开并且我可以写入它,如果文件没有打开(之前没有创建过)程序创建它. 所以问题是当我创建一个 .csv 文件并完成写入并且我想检查写入的内容是否真的存在时,文件无法打开。在 .txt 文件中,一切都是空白的。
回答by Software_Designer
datoteka.open(filename, std::fstream::in | std::fstream::out | std::fstream::app);
works fine.
datoteka.open(filename, std::fstream::in | std::fstream::out | std::fstream::app);
工作正常。
#include <fstream>
#include <iostream>
using namespace std;
int main(void)
{
char filename[ ] = "Informacije.txt";
fstream appendFileToWorkWith;
appendFileToWorkWith.open(filename, std::fstream::in | std::fstream::out | std::fstream::app);
// If file does not exist, Create new file
if (!appendFileToWorkWith )
{
cout << "Cannot open file, file does not exist. Creating new file..";
appendFileToWorkWith.open(filename, fstream::in | fstream::out | fstream::trunc);
appendFileToWorkWith <<"\n";
appendFileToWorkWith.close();
}
else
{ // use existing file
cout<<"success "<<filename <<" found. \n";
cout<<"\nAppending writing and working with existing file"<<"\n---\n";
appendFileToWorkWith << "Appending writing and working with existing file"<<"\n---\n";
appendFileToWorkWith.close();
cout<<"\n";
}
return 0;
}
回答by Raj Parihar
If filename does not exist, the file is created. Otherwise, the fstream::app, If file filename already exists, append the data to the file instead of overwriting it.
如果文件名不存在,则创建该文件。否则, fstream::app, 如果文件 filename 已经存在,则将数据附加到文件而不是覆盖它。
int writeOnfile (char* filetext) {
ofstream myfile;
myfile.open ("checkSellExit_file_output.csv", fstream::app);
myfile << filetext;
myfile.close();
return 0;
}