read and write.

I just want to change the contents of file into one line. Can you tell me the error, please? Thank you for your help!

#include <fstream>

using namespace std;

int main(){
ifstream fin;
ofstream fout;
char ch;
fin.open("source_code_contents.txt");
while(fin.get(ch)){
if(ch!='\n'){
fout.put(ch);
}
}
fout.open("source_code_contents_out.txt");
fin.close();
fout.close();
return 0;
}
It looks like you are trying to put() into the out- file before you open() it. By the way, you can't open the same file for reading and writing the way you are trying to. Just open the file, read it into memory, remove all newlines, then output.
Generally you need to open all files before you can use them. It is also a good idea to check to see if there wasn't a problem opening them, especially in this case. I am not sure if c++ will let you do this, with out some special things going on.

Example:
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
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
   ifstream inFile;
   ofstream outFile;
   char aChar;

   inFile.open("InTextFile.txt");
   if(inFile.good())  // if the file had a good open or not.
   {
        outFile.open("OutTextFile.txt");
        if(outFile.good())
        {
               while(!inFile.eof())
               {
                     inFile.get(aChar);
                     if(aChar != '\n')
                     {
                          outFile.put(aChar);
                      }
                }

               inFile.close();
               outFile.close();
         }
         else
         {
              cout << "Outfile couldn't open!!" << endl;
         }
    }
    else
    {
           cout  << "inFile couldn't open!!" << endl;
     }
} // end of main. 


Modifing the same file with two different streams might generate an error, but not sure what type. I don't know if this can be done in even a multi-threaded program. I would bet it would be a exception fault because how the os's might handle this.
Last edited on
Topic archived. No new replies allowed.