Hello everyone, I am new to this forum and I challenge getting my code to read text file located on the desktop. When I ran this code, a fatal error message shows like: No such file or directory
Thank you MiiNiPaa. The error message was cancelled, but I still cannot read the text file from my computer. My aim is to read a file from the computer and then create another file in which I will write the read texts. The code I wrote for the task is:
Your code as it stands right now just opens the file. By read if you mean to print the contents of the file to the console you can do something like this.
#include <iostream>
#include <fstream>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int main ()
{
std::ifstream ifs;
ifs.open ("example.txt", std::ifstream::in);
char c = ifs.get();
while (ifs.good())
{
std::cout << c;
c = ifs.get();
}
ifs.close();
return 0;
}
or if you've tried to extract information from your file in some other manner and that code fails post it here.
Thanks Salman. The code worked, but it copied the input file simply as characters. The contents of the input file are matrices like this:
10 20 30 40 50
20 30 40 50 60
30 40 50 60 70
I need to copy it and save them on the output file as same.
Sorry i can't get you ..... If you wanna say that you have integers in file and i am reading file as characters ??? Is that the problem???
If yes then This is not a problem ......You should not confuse yourself
The above logic will work just fine .. You are just copying files ....
oh realy i didn't consider that mistake ......
Thank you ...
But will you plz tell me what could be the possible solution and what will be replacement for eof()???
plzzzz...
you can also check if loop was terminated because you hit end of file or encountered an error after the loop:
1 2 3 4
if (infile.eof())
std::cout << "file is completely read";
else
std::cout << "There was an error...";
Another bonus of this code is that it captures not only end of file but other errors too, preventing possible infinite loop.
Example of infinite looping:
1 2 3 4 5
std::istringstream in("Hello, world!");
int i;
while(!in.eof()) { //infinite loop
in >> i; //fails without reading a single character. eof() is not set
}