Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mark5907

macrumors newbie
Original poster
Jan 24, 2010
2
0
I just start learning c++ programming and I am using xcode on my mac.


I have a question about file I/O(maybe a very silly one)
I tried to open Scopy.cpp and copy the content to another file Scopy2.cpp.
I put both of the file in the directory same as the project.
#include <string>
#include <fstream>
using namespace std;

int main() {
ifstream in("Scopy.cpp"); // Open for reading
ofstream out("Scopy2.cpp"); // Open for writing
string s;
while(getline(in, s)) // Discards newline char
out << s << "\n"; // ... must add it back
}


but nothing happened after I run the code.


Please tell me how to do it in the right way?
 
thank you for you help, but I think we are not on the same page.

I copy the example from the book "thinking in c++ volume 1"

I tried the website, and use the following example from it.

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

int main () {

ifstream ifs ( "test.txt" , ifstream::in );

while (ifs.good())
cout << (char) ifs.get();
ifs.close();

return 0;
}


I made a file test.txt and type some random words in it. I put it in the working directory. but this is what I got after I run the code


Loading program into debugger…
Program loaded.
run
[Switching to process 3551]
Running…

Debugger stopped.
Program exited with status value:0.
 
Works like a champ here :

Code:
$ cat test.cpp
#include <iostream>
#include <fstream>
using namespace std;

int main () {

ifstream ifs ( "test.txt" , ifstream::in );

while (ifs.good())
cout << (char) ifs.get();
ifs.close();

return 0;
}
$ cat test.txt
allo
allo
allo
allo
$ g++ -o test test.cpp
$ ./test
allo
allo
allo
allo

Are you sure your program is finding the test.txt file ?
 
Make sure your test text file is in the project directory. If your file isn't in it, then you'll run into issues unless you put in the exact path.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.