writing to a text file

I am trying to write to a .txt file lyingon my desktop but it is not working. If anyone can help me out. The code is as below.

#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;

int main () {
ofstream myfile;
myfile.open("C:\\users\\Desktop\\Jaswinder\ Singh\\myfile.txt", ios::out|ios::app);
//myfile.open("C:/users/Desktop/Jaswinder Singh/myfile.txt", ios::out|ios::app);
//myfile.open("myfile.txt", ios::out|ios::app);
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}

I tried with slash and backslash options as per some details available on other websites.
What do you mean "doesn't work"?

Does it compile?
Does it crash when you run it?
Is a file created?
Is it empty?
Do you see only "myfile" when looking on your desktop, or using file explorer?

Maybe at least add the error checking to see if the file was opened.
http://www.cplusplus.com/reference/fstream/ofstream/is_open/

The single forward / separator should work just fine.

Hello Beginner of C,


PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
#include<fstream>
#include<iomanip>

using namespace std;

int main()
{
	ofstream myfile;

	myfile.open("C:\\users\\Desktop\\Jaswinder\ Singh\\myfile.txt", ios::out | ios::app);

	//myfile.open("C:/users/Desktop/Jaswinder Singh/myfile.txt", ios::out|ios::app);
	//myfile.open("myfile.txt", ios::out|ios::app);

	myfile << "Writing this to a file.\n";

	myfile.close();

	return 0;
}

On line 11 you missed a backslash after "Jaswinder" and I do not believe that a space is allowed before "Singh" unless the directory name is "Jaswinder Singh" then you need to remove the "\".

Line 14 should open the file in the same directory as the "main.cpp" file.

Something you can add to your code:
1
2
3
4
5
6
if (!mfile)
{
	std::cout << "\n File " << std::qouted(outFileName) << " did not open" << std::endl;
	std::this_thread::sleep_for(std::chrono::seconds(3));  // <--- Needs header files chrono" and "thread".
	return 1;  //exit(1);  // If not in "main".
}

This can help with an output file stream, but the concept is more important for an input file.

Since you defined "myfile" as an "ofstream" the ", ios::out | ios::app" is not needed because the stream is opened gor output and append by default.

It looks like the path to the file is the problem. It makes no difference if you use a backslash or forward slash.

Hope that helps,

Andy
Some OS do allow space or leading space folder names. I don't think current windows will do it; you can't do it easily, but I didnt try very hard. I avoid them as they make the syntax for commandline interface that much more annoying.
Thanks everybody for your help.
Andy I have made the changes as you suggested. The code is as below. "Jaswinder Singh" is the directory name. As I could not understand the chrono and thread concept, i skipped that for now to understand the basic and leave that as next step. But no option is working out of the three myfile.open() commands. PLease help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
#include<fstream>
#include<iomanip>

using namespace std;

int main()
{
	ofstream myfile;

	myfile.open("C:\\users\\Desktop\\Jaswinder\ Singh\\myfile.txt");

       //myfile.open("C:\\users\\Desktop\\Jaswinder Singh\\myfile.txt");

	//myfile.open("C:/users/Desktop/Jaswinder Singh/myfile.txt");
	
	myfile << "Writing this to a file\n";

	myfile.close();

	return 0;
}
P.S. I have already kept a file text file named "myfile" on the desktop. I ran the code on Codeblocks as well as tried on an online IDE also but it did not run.
With a "\" before "Singh" it gives error "unknown escape sequence: '\040'.

And without a "\" before "Singh" it simply did not compile.
Put the file in a subfolder where it DOES NOT NEED A SPACE IN THE PATH OR FILE NAME.

Better still, put it in the same folder as the executable, remove any path before the file name, and run it in the simple windows command window, not codeblocks.
try myfile.open("\"C:\\users\\Desktop\\Jaswinder Singh\\myfile.txt\"");

\ space is not an escape sequence. there are only a few escapes... \\ one slash, \" one quote, end of lines (\n \r \c) and tabs \t and a couple of other similar. you can already type space, so \space has no meaning.

commandline windows likes quotes around spaced out file names, that is what I gave you to try.
Last edited on
Don't confuse what cmd needs to express the path name on the command line with what the actual code needs. You don't need quotes. You don't need to quote the spaces with backslashes. You do need to quote the backslashes themselves to get them into a string literal.

I suspect that one of the directories doesn't exist. Use the C library to get meaningful error diagnostics, at least temporarily:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cstdio>
#include <cerrno>
#include <cstring>

int main()
{
    FILE *fp = std::fopen("C:\\users\\Desktop\\Jaswinder Singh\\myfile.txt", "w");
    if (fp) {
	std::cout << "Opened successfully\n";
	fclose(fp);
    } else {
	std::cout << "Can't open file. "
		  << "Errno=" << errno
		  << ": "
		  << std::strerror(errno)
		  << '\n';
    }
}
Fair enough.
option 2, perhaps your executable lacks permission to write to your desktop (weird, but possible). Or, this is someone else's desktop, and you lack permission (very possible?).
Hello Beginner of C,

Sorry for the delay I have not been feeling well the last two days.

I suspect that your path of "C:\\users\\Desktop\\Jaswinder Singh\\myfile.txt" is is incorrect.

Using Windows Explorer when I went to set up the same path I ended up with:
C:\Users\Andy\Desktop\Jaswinder Singh. "Andy" is what Windows came up with when I first turned on the computer and answered the questions. To use this you can either excapt the "\"s or use a forward slash. You will also need one at the end of "Singh" before the file name. Which would be:
C:\\Users\\Andy\\Desktop\\Jaswinder Singh\\myfile.txt" . Where "Andy" will likely be your first name.

Using Windows Explorer at the top of the window just above the directory listing you will see: This PC > Windows(C:) > Users > .... When you get to where you want click to the right of the words and it will change to the path starting with "C:\...".

I feel that you are missing a sub-directory between "users" and "desktop" and that is why it can not find the file.

Hope that helps,

Andy
Thanks a lot Andy and everyone else. I am able to write to the file.
Hello Beginner of C,

The following program illustrates a different, I feel a better, way to deal with your problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<iostream>
#include<iomanip>
#include <chrono>
#include <thread>

#include<fstream>
#include <Windows.h>  // <--- For "GetLastError()" function.

//using namespace std;  // <--- Best not to use.

int main()
{
	const std::string PATH{ "C:\\users\\Desktop\\Jaswinder Singh\\" };

	const std::string outFileName{ "myfile.txt" };

	std::ofstream outFile(PATH + outFileName);

	if (!outFile)
	{
		std::cout << "\n File " << std::quoted(outFileName) << " did not open" << std::endl;

		std::cout << "\n  Error number is: " << GetLastError() << ' ';

		if (GetLastError() == 3) std::cout << std::quoted("ERROR PATH NOT FOUND") << std::endl;

		std::this_thread::sleep_for(std::chrono::seconds(5));  // <--- Needs header files chrono" and "thread". Optional as is the header files.

		return 1;  //exit(1);  // If not in "main".
	}

	//myfile.open("C:\\users\\Desktop\\Jaswinder Singh\\myfile.txt"); // <--- Better, but missing a subdirectory.

	//myfile.open("C:/users/Desktop/Jaswinder Singh/myfile.txt"); // <--- Will work, but still missing a subdirectory.

	outFile << "Writing this to a file\n";

	outFile.close();

	return 0;
}

To start with lines 2 and 3 like line 27 are optional. In my set up for VS when a return or exit function is executed the window, the program is running in, closes. This allows me to see the message before it is gone. Although optional, if the program was compiled for release line 27 may be useful.

The only part of line 27 you need to understand is: seconds(5). as the name implies the "5" is whole seconds. You could use "milliseconds" where (1000) is equal to one second and say (500) is equal to 1/2 second and (1500) is 1 and 1/2 seconds. It gives more control over the wait time. This is one of the nicer parts about C++. You do not always have to know how something works just how to use it.

Lines 23 and 25 I added for this example to help show what the problem is. Normally I do not put these lines in the if block.

Lines 13 - 30 is an overall concept. I tried to make its use as generic as I could and that is why I put the file name in a variable with line 15. Most of the time I leave out lines 23 and 25. /when learning about files I found this to be useful to understand what is happening.

The similar concept:
1
2
3
4
5
6
7
8
9
10
const std::string inFileName{ "" };  // <--- File name goes here.

std::ifstream inFile(inFileName);

if (!inFile)
{
	std::cout << "\n File " << std::quoted(inFileName) << " did not open" << std::endl;
	std::this_thread::sleep_for(std::chrono::seconds(3));  // <--- Needs header files chrono" and "thread". Optional as is the header files.
	return 1;  //exit(1);  // If not in "main".
}

For an input file this is a must have. Not so much for an output file, but it is helpful as it is with your problem.

For an output file is the file name does not exist it will create the file when the file stream is opened. Unlike the input file which has to exist first.

Line 17 and line 3 in the second bit of code does two things. First it creates the file stream and then opens the file in one line of code.

Note: The path here is purposely incorrect to illustrate the use of the if statement. Lines 32 and 34 I think the comments explain it.

Anything you do not understand let me know.

Hope this helps,

Andy
Registered users can post here. Sign in or register to post.