input/output with files

May 24, 2008 at 3:38pm
I saw a code to make an output to a file in the tutorial:
1
2
3
4
offstream.file;
myfile.open("file.txt")
myfile<<...;
myfile.close()

But i'd like to put in the place of ("file.txt) an user-defined string or character like:
1
2
string path;
getline(cin,path);

or
1
2
char path;
cin>>path;

I want to create a 'notepad',but i could only create a reader and a writer,which could create and read a file called Notepad.txt,so i really want to know how to put defferent pathes there.(i'm a beginner in c++)
Last edited on May 24, 2008 at 3:45pm
May 24, 2008 at 10:41pm
You'll find that the C++ reference on this site is top-notch.

Never use cin >> s for any string that is expected to contain whitespace. Always use getline().

Open the file with
1
2
myfile.open( path.c_str() );
if (!myfile) fooey();


Writing a text editor is probably the quintessential first major programming effort. (I'm still working on mine :-)

If you want it to be a GUI (Windows) program, you'll have to either use the Win32 API directly (which is pretty straight-forward, but a little overwhelming at first), or a GUI toolkit like FLTK, GTK+, Qt, etc.

If you want it to be a CUI (Text-mode) program, you should check out the Curses library.
PDCurses on Windows: http://pdcurses.sourceforge.net/
NCurses on Unix/Linux/OS X: http://www.gnu.org/software/ncurses/

Hope this helps.
Last edited on May 24, 2008 at 10:43pm
May 25, 2008 at 4:30am
This is my final MS-DOS version.I have separate programs for writing and reading.
The writer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;

int main()
{string path;
string text;
cout<<"Enter the name and path of the file"<<endl;
getline(cin,path);
cout<<"Enter the text"<<endl;
getline(cin,text);
ofstream file;
file.open(path.c_str());
file<<text;
file.close();
return 0;  
}

reader:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;

int main()
{string path,line;
cout<<"enter the name and path of the file"<<endl;
getline(cin,path);
ifstream file;
file.open(path.c_str());
          while(!file.eof())
          {
                 getline(file,line);
                 cout<<line<<endl;
           }
file.close();
return 0; 
}
Topic archived. No new replies allowed.