[Solved] Cannot create a txt file using fstream::open


Point 1: You cannot open to read if the file doesn’t exist. Fortunately you probably don’t want to. Simultaneously reading and writing the same file is problematic and almost always a bad idea. Until you know you have to read and write at the same time,

  1. open the file for reading
  2. read in the file
  3. close the file.
  4. edit the file in memory
  5. open the file for writing
  6. write out the file
  7. close the file

If you have a really big file you can’t store in memory,

  1. open the file for reading
  2. open a temporary file for writing
  3. read in part of the file
  4. edit the part you read
  5. write the part you read to temporary
  6. if more file, goto 3 (but don’t use goto), else continue
  7. close file
  8. close temporary file
  9. delete file
  10. rename temporary file to file

Point 2: You have created the txtfile folder, but have you created it in the right place? Your development environment (include of conio.h suggests Visual Studio or antique) may not be running your program from where you think it is running.

Add this to your code in main:

char buf[4097]; // really big buffer
getcwd(buf, (int)sizeof(buf)); // get working directory
std::cout << buf << std::endl; // print the working directory

If the folder printed out is not where you made the txtfile folder, you can’t open the file. If you want to automatically make the folder, read here: How to make a folder/directory

Point 3: exit(1); is a really big hammer. It is a nasty hammer. Read more here. Don’t use it without a really, really good reason. In this case return is more than enough to get you out of the function, and if you add a return value to the function, main can test the return value to see if it should continue or return. Or you can throw an exception.

2

solved Cannot create a txt file using fstream::open