0

I am simply trying to get a program to write "Test" to a created file. However, when I run the code below there is no file in the working directory. I am running this code on a Mac and compiling using gcc from Terminal.

    // writing on a text file
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile ("example-1.txt");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    if (myfile.fail())
       cout << "Fail" << endl;
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}
JOG-Design
  • 207
  • 2
  • 5
  • 14
  • Does anything get cout? – GermaineJason Mar 25 '14 at 03:08
  • Please show the exact command you use to compile, and the exact command you use to execute. – paddy Mar 25 '14 at 03:10
  • 2
    Is the location writable ? What is the output of the program ?. How are you compiling and executing the program. Also it looks like you are using gcc which is GNU C compiler to compile a c++ program. For a c++ program use g++ g++ -g -o – Srikan Mar 25 '14 at 03:28
  • 1
    you may be better off checking `if (!myfile.good())` immediately after opening the file then `cout << "Unable to open file" << endl;` also you aren't opening the file in this case, you are checking to see if it is open, try `myfile.open()`. Another thing is to check file permissions – Matthew Pigram Mar 25 '14 at 03:33
  • Ah sorry just realised your are opening the file using the constructor, perhaps add a try catch block to your file operations. – Matthew Pigram Mar 25 '14 at 03:39
  • How are you running the program? Give full path to the file in the `ofstream` statement. – cppcoder Mar 25 '14 at 04:08
  • Do you have permission in that directory? – orezvani Mar 25 '14 at 06:03

2 Answers2

0

All the code I posted is valid and works. However, I was compiling via the command line on a Mac OSX using gcc. The command looks like this:

g++ -g nameofinputfile.cpp -o nameofoutput.out

This works fine, however when you open the .out file (compilation file) the example-1.txt file is created at the root of the Users file where Documents, Desktop, Downloads etc. exist. Simply you just have to state where it is to be created. Refer to this question to learn how to specify the directory in your code.

Community
  • 1
  • 1
JOG-Design
  • 207
  • 2
  • 5
  • 14
0

You must use of fprintf() for write text on text files. For example :

fp1=fopen("report.txt","a+");
fprintf(fp1,"Port is open: %d\n\n",i);
fclose(fp1);
hmd_1369
  • 1
  • 2