Does anyone know why fstream crashes at this line? - c++

This is the first time i ran into this problem so I have no idea how to fix it.
EDIT: Nevermind. Look like an off by one error in my constructor caused this to happen somehow
#include <iostream>
#include <fstream>
#include "graphm.h"
using namespace std;
int main() {
ifstream infile1("data31.txt");
for(;;){
GraphM G;
G.buildGraph(infile1);
if (infile1.eof())
break;
}
void GraphM::buildGraph(ifstream& infile){
int i = 0;
infile >> i; //it crashes here
}
my text file is just 1 line:
5

The problem might be related to the file not being open. You should always check whether a file has been successfully opened:
ifstream infile1("data31.txt");
if ( !infile1 )
{
// Failed to open data31.txt
return -1;
}
or you can use an explicit function instead of overloaded operator!
if ( infile1.fail() )
{
return -1;
}

What is the error that you get? Make sure that the file is open by checking the infile.is_open() function. you can find the sample code here:
http://www.cplusplus.com/reference/iostream/ifstream/is_open/
You can also check this thread:
Using C++ ifstream extraction operator>> to read formatted data from a file
It has a useful instructions for using ifstream.

Possible problems with the code:
1. Unopenable file/unopened file
2. Unopenable file/unopened file
3. Unopenable file/unopened file
4. Unopenable file/unopened file
How to get around this problem? Follow #MaximSkurydin's code.

Related

Input Output with fstream

Can anyone tell me what is wrong with this code? I always get not open.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
fstream fs;
fs.open("fsfile2",ios::in|ios::out|ios::binary);
if(fs.is_open()){
fs.write("wow",sizeof("wow"));
char str[20];
fs.read((char*)str,sizeof(str));
cout<<str<<endl;}
else
cout<<"Not open\n";
return 0;
}
Try this code
fs.open("fsfile2", ios::app|ios::in|ios::out|ios::binary);
By using the open() like you are that file will not be created if that is your goal.
If you want to create a new file please look at: fstream won't create a file
If the file exists, you are not looking for it in the right path. Or change the file name to the full path or put the executable in the folder where the file is.
Hope this helps.
Probably, you do not have permissions to create files in the directory, where your executable is.
Solution:
Please add a file extension to the filename.
If it's a text file, it will be
"fsfile2.txt"
Then, I tried removing
ios::in
since the first process only writes to file, and by removing that, the file is created and "wow" is also written at it.
In order for these lines
fs.read((char*)str,sizeof(str));
cout<<str<<endl;
to work,
You need to close the stream after writing to it, then open the stream in read mode, then read the contents. Take note that closing the stream will save the edited file.
Additional:
You can also change
fs.write("wow",sizeof("wow"));
to
fs << "wow";
You can do the same when reading from file,
fs >> str;
You can also use the string class of C++, instead of char array so that the number of characters inside the file won't be your problem anymore.
#include <string>
string str;
Checking for EOF (end-of-file) is recommended since files are read line by line. Once you add a new line and add a character to the line, the code that doesn't loop until EOF will only read the first line of the file.
In order to solve this, it is recommended to loop until EOF is reached.
while(!fs.eof()) {
fs >> str;
cout << str << endl;
}
So here is the improved snippet:
#include <string>
fs.open("fsfile2.txt", ios::out); // ios::out for write only
if(fs.is_open()) {
// writes "wow" to file
fs << "wow";
// closes the file
fs.close();
// ios::in for read only
fs.open("fsfile2.txt", ios::in);
// better to define variable just before using it
string str;
// loops until end-of-file
while(!fs.eof()) {
// reads a line from file, stores it to str
fs >> str;
// shows str to screen
cout << str << endl;
}
}
*Note: I removed
ios::binary
Since your code is not dealing with binary files yet.
I tried these and it worked fine! Have a nice day!
fstream fs; does not create a new file for you.
You need to make sure that the file exists in your project directory.
On the other hand, if you were to use ofstream fs("file.txt"); it would create the file for you. Or use only ios::out when you open fstream fs, this will create the file for you.

Editing a text file

I want to edit a text file, but I'm stuck in finding the correct functions or methods to do so.
So far I'm able to open a text file and look for a certain string, but I have no idea on how to move the cursor, add or replace information, steps 4 - 7 in my pseudocode shown below.
Can you provide some guidance? Which functions should I use (in case they already exist)?
A sample 'easy' code would be appreciated as well.
Pseudocode:
1. Open file.
2. While not eof
3. Read file until string "someString" is found.
4. Position the cursor at the next line (to where the someString was found).
5. If "someString" = A go to step 6. Else go to step 7.
6. Replace the information in whole line with "newString". Go to step 8.
7. Add new information "newString_2", without deleting the existing.
8. Save and close the text file.
Thanks.
I would recommend to put the getline command into the while loop because then it won't stop only because of EOF but when getline is not able to read anymore.
Like when the error bad occurs (which happens when someone deleted the file while your program was reading it).
It seems like you want to search inside a string, so "find" might be quite helpful.
#include <iostream>
#include <fstream>
#include <string>
int main (){
std::fstream yourfile;
std::string line, someString;
yourfile.open("file.txt", ios::in | ios::app); //The path to your file goes here
if (yourfile.is_open()){ //You don't have to ask if the file is open but it's more secure
while (getline(line)){
if(line.find(someString) != string::npos){ //the find() documentation might be helpful if you don't understand
if(someString == "A"){
//code for replacing the line
}
else{
yourfile << "newString_2" << endl;
}
} //end if
} //end while
} //end if
else cerr << "Your file couldn't be opened";
yourfile.close();
return 0;
}
I can't tell you how to replace a single line in a text file but I hope you can work with that little I can give you.
This should be a good start:
// basic file operations
#include <string>
#include <fstream>
int main ()
{
std::fstream myfile;
std::string line;
while (!myfile.eof())
{
std::getline(myfile,line); // Check getline() doc, you can retrieve a line before/after a given string etc.
//if (line == something)
//{
// do stuff with line, like checking for content etc.
//}
}
myfile.close();
return 0;
}
More informations here

read and write a binary file in c++ with fstream

I'm trying to write simple c++ code to read and write a file.
The problem is my output file is smaller than the original file, and I'm stuck finding the cause.
I have a image with 6.6 kb and my output image is about 6.4 kb
#include <iostream>
#include <fstream>
using namespace std;
ofstream myOutpue;
ifstream mySource;
int main()
{
mySource.open("im1.jpg", ios_base::binary);
myOutpue.open("im2.jpg", ios_base::out);
char buffer;
if (mySource.is_open())
{
while (!mySource.eof())
{
mySource >> buffer;
myOutpue << buffer;
}
}
mySource.close();
myOutpue.close();
return 1;
}
Why not just:
#include <fstream>
int main()
{
std::ifstream mySource("im1.jpg", std::ios::binary);
std::ofstream myOutpue("im2.jpg", std::ios::binary);
myOutpue << mySource.rdbuf();
}
Or, less chattily:
int main()
{
std::ofstream("im2.jpg", std::ios::binary)
<< std::ifstream("im1.jpg", std::ios::binary).rdbuf();
}
Two things: You forget to open the output in binary mode, and you can't use the input/output operator >> and << for binary data, except if you use the output operator to write the input-streams basic_streambuf (which you can get using rdbuf).
For input use read and for output use write.
There are 3 problems in your code:
1- You have not opened your output file in Binary.
2- Your code return "1", normally you should return "0", if something went wrong then return an error code.
3- You should use "manipulators" and make c++ not to avoid whitespaces, so in order to read from file instead of:
mySource >> buffer;
you should use:
mySource >> std:noskipws >> buffer;
Well, its just because of padding at the end of the image. eof of any file do not include the padded bytes added at the end of file.
Try this
take img1.jpg contains 20 space charecter at the end not visible here (uegfuyregwfyugwrerycgerfcg6ygerbucykgeugcrgfrgeyf ) and run your program (do not include parenthesis in the file, these are used to show the data content)
you will see img2.jpg contains (uegfuyregwfyugwrerycgerfcg6ygerbucykgeugcrgfrgeyf)
So, its better option to read the file byte by byte using the filesize which you can get using stat, and run for loop till filesize. Hope this should resolve your problem you mentioned above

Cannot read text file in C++

I am stumped by this simple problem. I am reading a text file with C++:
std::ifstream stream;
stream.open(filename);
if (!stream)
cout << "Invalid stream" << endl;
And !stream is true but there seems to be nothing wrong with the text file. Under what circumstances can stream be false?
Note: is_open returns true
You have not provided enough information. Nevertheless, my psychic powers reveal:
filename is a relative path, and your current working directory is not what you think it is.
Inside your if clause, before printing via std::cout, add this:
perror(filename.c_str());
This code works for me:
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
std::ifstream infilestream;
std::string line;
infilestream.open("test.txt");
while(infilestream)
{
std::getline(infilestream, line);
cout<<line<<"\n";
}
infilestream.close();
return(0);
}
chances are your file is inaccessible OR you might not have enough privileges to access the file.
Maybe its open somewhere else? Check if the path to the file is right.

C++: how can I write a program to read integers from a file?

When I use the code recommended in the book, I get an error. I am using NetBeans 6.8 for Mac.
Here is the code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile;
int number;
inputFile.open("MacintoshHD/Users/moshekwiat/Desktop/random.txt");
inFile >> number;
cout<<endl <<number<<endl;
inputFile.close();
return (0);
}
Here is the error:
main.cpp:20: error: 'inFile' was not declared in this scope
What needs to be done??
Thank You
Replace inFile with inputFile.
Problem 1 (the one the compiler sees) is a simple typo: inFile should be inputFile. Do make sure you check for typos like this before posting to Stack Overflow.
Problem 2: the path name to your file is probably wrong, and generally, when you try to read from a stream that couldn't be initialized properly because the file couldn't be opened, you'll get 0.
In this case the path you specified is a relative path to the file from the directory your program was launched in, so whatever directory you ran the program from would need a subdirectory called "MacintoshHD", then "Users", then... you get the idea. To get the correct path, right-click on the file in the Finder and select "Get Info". Under "Where: " you'll see the correct path to the directory that contains your file; it will probably say "/Users/moshekwiat/Desktop". Add "/random.txt" to that and that should be the path you use.
Normally, C++ programmers will write code to make sure the file opens correctly before reading from it. A simple way to check for that after initializing inputFile, but before trying to read from it is:
if (! inputFile) {
cerr << "Could not open the file!" << endl;
return 1; // returning non-0 status is customary
// if your program encounters an error
}
Change inFile to inputFile
For a start, there's no 'inFile' object in your code.
inFile >> number;
Look again:
ifstream inputFile;
change inFile to inputFile
Use inputFile instead of inFile