Writing CRC data to .txt file - c++

This seems like it should be a basic C++ process, but I'm not familiar with the data output.
When I print the data without outputting to a text file, I get the correct values.
example: 00150017000 181
When printing to a text file, this is what I get:
11161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116111611161116
Here is my code:
ofstream myfile;
myfile.open("C:\\CRC.txt");
for (i = 0; i < 200; i++, id++)
{
myfile << sprintf(idstring, "%011d", id);
myfile << printf("%s %03d\n", idstring, computeCrc(idstring));
}
myfile.close();
Everything else works fine and I know the CRC is generated correctly. Just a matter of getting the correct output.
I was able to output the console screen to a text file by adding "> CRC.txt" to the Debugging Properties Command Arguments, but I just wanted to know how I could incorporate the ofstream method into this.
Thanks in advance.

You don't save to the file what you think you save. First you save the result of sprintf() function, which in your case is 11. Then you save the result of the printf() function which in your case is 11 + 1 (space) + 3 + 1 (\n) = 16. So the result is 200 times 1116.
What you wanted to do
char tempBuf[12];
ofstream myfile;
myfile.open("C:\\CRC.txt");
for (i = 0; i < 200; i++, id++)
{
sprintf(tempBuf, "%011d", id);
myfile << tempBuf << ' ';
sprintf(tempBuf, "%03d", computeCrc(tempBuf));
myFile << tempBuf << '\n';
}
myfile.close();

You are ouputing the return of sprintf() and printf() to the file. The returns of sprintf() and printf() are int and not the string you are creating. To output the string you need to change your code to
for (i = 0; i < 200; i++, id++)
{
sprintf(idstring, "%011d", id);
myfile << idstring;
myfile << computeCrc(idstring) << endl;
}

Related

Error opening a text file using ifstream c++11

I am creating an object called SpellChecker that corrects the spelling of words in a string.
To check if the words are spelled correctly and if not to correct them, I have a text file of correct words (one per line). I also have a text file of words that are misspelled and their corrections separated by a tab.
My issue is reading in my text file. I have created an if statement to see if my file opens successfully. However, I believe my file should be readable and it is not. I am trying to find out why this is happening.
Here is my SpellChecker constructor:
SpellChecker::SpellChecker(string tempLanguage, string correctWordsFile,string wordCorectionsFile){
language=tempLanguage;
ifstream istream;
istream.open(correctWordsFile);
if(!istream.is_open()){
cout << "Error opening " << correctWordsFile << endl;
}
int count=0;
string temp;
while(!istream.eof()){
getline(istream,temp);
correctWords[count] = temp;
count++;
}
numCorrectWords = count;
istream.close();
istream.open(wordCorectionsFile);
if(!istream.is_open()){
cout << "Error opening " << wordCorectionsFile << endl;
}
int j=0;
int i=0;
char temp2;
while(!istream.eof()){
istream.get(temp2);
if(temp2 == '\t'){
j++;
}
else if(temp2 == '\n'){
i++;
j = 0;
}
else
wordCorections[i][j] += temp2;
}
numwordCorrections = i;
istream.close();
}
Here is my main:
int main(){
SpellChecker spellCheck("English","CorectWords.txt","WordCorections.txt");
spellCheck.viewCorrectWords();
spellCheck.viewCorrectedWords();
spellCheck.setEnd('~');
spellCheck.setStart('~');
cout << spellCheck.repair("I like to eat candy. It is greatt.");
}
The terminal returns:
"Error opening CorectWords.txt"
How can I solve this problem?
The call to library function is_open() is returning false, which could be due to one of many reasons.
Ensure that :
1. You have used correct name of the data file.
2. The data file is in the same folder as the executable of your program.
3. It has been closed by any previous program that read it.

c++ reading line by line but not able to show output line by line

I am trying to run a C++ code. My input file has number of lines and I am trying remove the spaces in each line and then display. But, when i run the code the output is coming in a single line i.e all thelines of the file are being shown in one single line.
Please solve my problem , so that i get the output line by line.
Thanks.
I have tried this code. This is my code:
int main()
{
int i = 0, len, j;
std::string str;
ifstream iFile("g.txt");
while (std::getline(iFile, str) != 0)
{
len = str.length();
for (i = 0; i < len; i++)
{
if (str[i] == ' ')
{
for (j = i; j < len; j++)
{
str[j] = str[j + 1];
}
len--;
}
}
cout << str;
}
}
cout<<str; is going to write the string to the output buffer and that is it. The next time you call it the str you write out will start right after that last str that was written. If you want each str on its own line then you can use
cout << str << endl;
//or
cout <<str << "\n";
The reason each line does not retain its newline character is that getline() reads until it encounters a newline and then stores everything up to that newline in the string. It then tosses that newline out instead of adding it to the string.
You are writing like this:
cout<<str;
You need to output the new-line after your string, which is done as follows:
cout<<str<<endl;

C++: Why is ofstream not appending or creating new files?

i have a little problem with ofstream. My main calls a certain class several times, each time with different parameters for testing purposes
ImageComparison* imco = new ImageComparison(queries[i], j, k, l);
Inside each instance i want a formatted output to a file, so i first tried this
ofstream ofs;
ofs.open("somepath" + params + ".txt");
ofs << "write results";
ofs.close();
I expected that ofstream would create several files, due to different params and therefor different filenames, and write something into it. But it appears that it's always overwriting the former file and just saving the last instance.
Afterwards i tried to use one file over and over again and appending new lines, since this would be a better solution for my case
ofstream ofs;
ofs.open("somename.txt", ofstream::out | ofstream::app);
ofs << "write params";
ofs << "write results in same line";
ofs << endl;
ofs.close();
In this case it appears that it's not appending new lines, instead it overwrites the former line and in the end i just have the results of the last instance.
Please enlighten me, i don't have any ideas whats wrong here.
I appreciate any suggestions/solutions :)
EDIT: here is concrete case:
main:
vector<string> queries = {"apple","banana","book"...};
for(int i=0; i<18; i++) {
//if(i==1) break;
for(int j=0; j<3;) {
//if(j==2) break;
for(int k=10; k<800;) {
//if(k==400) break;
for(int l=50; l<600;) {
ImageComparison* imco = new ImageComparison(queries[i], j, k, l);
imco->DoImCo();
delete imco;
}
}
}
}
ImageComparison.cc:
string bloo = "../ImageData/" + m_object_type + "/" + m_object_type + "metric=" + to_string(m_metric) + ",hessian=" + to_string(m_hessian) + ",words" + to_string(m_number_of_words) + ".txt";
ofstream ofs;
ofs.open(bloo.c_str(), ofstream::out | ofstream::app);
for(int i=0; i<image_names.size(); i++) {
if(similarity_of_one[i] < similarity_average) {
ofs << " x";
}else{
ofs << " v";
}
}
ofs << endl;
ofs.close();
EDIT2: forgot parameter increase inside the "for's" but not important i think
Did you try starting a new project with only this part of your example code? Doesn't it append new lines for you?
Blockquote
ofstream ofs;
ofs.open("somename.txt", ofstream::out | ofstream::app);
ofs << "write params";
ofs << "write results in same line";
ofs << endl;
ofs.close();
Try to use ofstream::app only, it will automatically create new file for you. Frankly, I don't see any problem with the above code.
(Sorry I never made an answer. It looks lame :( )
Finally, i found something. It seems that there were a problem with the name. After using a constant name like "../Test.txt" it worked fine, sill don't know why but the problem is gone. Big thx for all your suggestions.

Extra File lines being overwritten when output is put into specificied file lines

Hey I have a bit of a silly question but I am having a bit of an issue with my code. I am trying to overwrite a line of a file, which is what it does, but the problem is that it overwrites other file lines as well. I am using C++ visual studios 2010. My code is below.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const string FILENAME = "DatabaseTest.txt";
fstream& GoToLineI(fstream& file, int num)
{
file.seekg(ios::beg);
for(int i = 0; i < num+1; i++)
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return file;
}
fstream& GoToLineO(fstream& file, int num)
{
file.seekp(ios::beg);
for( int i = 0; i < num; i++)
{
//gets the length of the line.
GoToLineI(file, i);
string s;
file >> s;
long pos = file.tellp();
file.seekp( pos + s.length() );
}
return file;
}
int main()
{
fstream myfile(FILENAME.c_str(), ios::out);
myfile.close();
myfile.open(FILENAME.c_str(), ios::in | ios::out);
myfile << "Usernames:" << endl;
for( int j = 0; j < 101; j++)
myfile << j << endl;
cout << "Where do you want to grab the data from?";
int i = 0;
cin >> i;
GoToLineI(myfile, i);
string line;
myfile >> line;
cout << line << endl;
GoToLineO(myfile, i);
if( myfile.is_open() )
{
cout << "File should be writeable" << endl;
myfile << "This should be at line 75" << endl;
}
myfile.seekp(ios::end);
system("PAUSE");
myfile.close();
return 0;
}
The issue may be in how I have my GoToLineO, which is how I find where to get to the output line, and It calls the GoToLineI in order to get the length of the lines until it reaches the right line to start displaying out put on. The output that this code generates is as such.
72
73
74
This should be at line 75
82
83
84
And it should look like this:
73
74
This should be at line 75
76
77
78
79
80
81
Any sort of insights or advice would be greatly appreciated.
edit: changed to only the important part of the outputs that should be shown.
If you seek to a spot in a file, and then start writing there, what you write is going to overwrite the exact same number of bytes as what you write -- a little like an editor that's always in overwrite mode instead of insert mode.
If you want your result to remain a simple text file, about all you can do is copy the data to a new file, inserting your new data in the right place, then copying the remaining data from the original file into the new file after the new data you inserted.
If you want that result to have the same name as the original, you have a few choices -- you can copy the entire result back to your existing file, or (if you aren't worried about the possibility of multiple hard links to the original file) you can delete the original file, and rename the new one to the old name.

Outputting multiple lines to a text file

I've done this before, but can't find the sample code...still new to c++.
I need to output multiple lines to a text file. Right now it only outputs the last line, so I assume its overwriting the prior line each time the loop is run. How do I get it to output a line and then output to the next line, etc. without writing over the prior line?
Here's a snippet:
int main()
{
int n = 1;
while (n <= 100)
{
int argument = 0 + n;
ofstream textfile;
textfile.open ("textfile.txt");
textfile << argument << endl;
textfile.close();
++n;
}
return 0;
}
Open the file before you enter the loop, and close it after you exit the loop.
It looks like the default open mode is override, so it's only going to write over anything in the file previously with what is being currently written into the file.
Below are to keep the file handle open instead of reopening many times. If you want to append still you should use this :
textfile.open ("textfile.txt", ios::out | ios::app);
This will open the file for output and append on the end of the file.
int main()
{
int n = 1;
ofstream textfile;
textfile.open ("textfile.txt");
while (n <= 100)
{
int argument = 0 + n;
textfile << argument << endl;
++n;
}
textfile.close();
return 0;
}
You should open and close the file outside of the loop. When the file is opened, it defaults to overwriting. You can specify an append mode, but since opening a file is a somewhat lengthy operation, you don't really want to do that in this case.
Use this instead :
int main()
{
int n = 1;
while (n <= 100)
{
int argument = 0 + n;
ofstream textfile;
textfile.open ("textfile.txt", ofstream::out | ofstream::app);
textfile << argument << endl;
textfile.close();
++n;
}
return 0;
}