Tìm thư viện mà mở file không có tồn tại thì tạo file

Có thư viện nào mà mở file không có thì tạo file mà không làm tác dụng phụ khác không?

#include <vector>
#include <iostream>

#include<stdlib.h>
#include<malloc.h>
#include<stdio.h>
#include<fstream>
#include<cstdio>

using namespace std;

typedef vector<int> intArray;

void main() {
#if 0
int i, m, n;
vector<intArray> a;
cout << "Nhap so luong dong, cot: "<<"\n\n";
cout<<"Nhap so luong dong : ";
cin>>m;
cout<<"Nhap so luong cot : ";
cin>>n;
a.resize(m);//resize là thay đổi kích thước mảng
for (i = 0; i < m; i++)
	a[i].resize(n);
#endif
ifstream f;

f.open("D:\hoangkiet1.txt",ios::app);
if (f == NULL)
printf("Khong mo duoc tap tin!\n\n");
else
{
	cout<<"mo duoc tap tin!"<<"\n\n";
}

f.read("D:\input.txt", 10);

//free(p);
system("pause");
}

Xem lại quy tắc đăng code lên DNH tại đây.


Một chút if else thôi mà, cần gì tìm thư viện.

#include <string>
#include <fstream>
#include <iostream>
 
int main()
{
    std::string filename = "example.123";
 
    std::fstream fs;
 
    fs.open(filename);
 
    if(!fs.is_open())
    {
       fs.clear();
       fs.open(filename, std::ios::out); //Create file.
       fs.close();
       fs.open(filename);
    }
 
    std::cout << std::boolalpha;
    std::cout << "fs.is_open() = " << fs.is_open() << '\n';
    std::cout << "fs.good() = " << fs.good() << '\n';
}

src

ủa ios::out là mở file có sẵn trở đi

cảm ơn anh :grin: :grin: :grin: :grin: :grin: :grin: :grin: :grin: :grin: :grin:

https://stackoverflow.com/a/18160837/10702045

Muốn biết đúng hay sai thì chạy thử.

Thì dùng lớp FILE, mở không được thì nó luôn có mã lỗi trả về. Nếu không có file thì tạo mới.
Cái này là cái cơ bản hay muốn ăn sẵn hơn nữa ? :slight_smile: