如果文件存在,请使用它;如果不存在,请创建它

编程入门 行业动态 更新时间:2024-10-19 02:18:25
本文介绍了如果文件存在,请使用它;如果不存在,请创建它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 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.

你好,所以我要从程序中检查文件是否已经存在,如果没有打开文件就可以打开程序,如果文件没有打开,我可以写入文件(还没有创建之前)创建程序.所以问题是当我创建一个.csv文件并完成写入时,我想检查写入的文件是否确实存在,无法打开该文件.在.txt文件中,所有内容均为空白.

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.

推荐答案

datoteka.open(filename, std::fstream::in | std::fstream::out | std::fstream::app); 效果很好.

datoteka.open(filename, std::fstream::in | std::fstream::out | std::fstream::app); works fine.

#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; }

更多推荐

如果文件存在,请使用它;如果不存在,请创建它

本文发布于:2023-10-23 05:40:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519956.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不存在   文件   使用它

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!