Substituting 0A For \n - c++

I'm at the time beginning the development of a simple hex editor(that only reads at the time). I want to substitute OA for "\n", I'm trying with this code:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
ifstream infile;
int crtchar = (int)infile.get();
infile.open("test.txt", ifstream::in);
while(infile.good())
{
if(crtchar != 0xA)
cout << hex << setfill('0') << setw(2) << crtchar << ":";
else
cout << endl;
}
cout << "\n=====================================\n";
infile.close();
return 0;
}
It compiles without errors, but when I try to execute it, I just got nothing:
C:\Documents and Settings\Nathan Campos\Desktop>hex
=====================================
C:\Documents and Settings\Nathan Campos\Desktop>
This is happening just after I've added the feature to substitute OA for \n, because before it was working very nice. What is wrong?

You realize that you are only reading a character once, and before even opening the file, at that?

Sigh. You try to read the file before you open it.

Shouldn't you first open(...) your file and then try to get() from it?
Also, shouldn't you do more get()'s inside your while loop

Put int crtchar = (int)infile.get(); inside a while(infile.good()) and give it a try.

Related

How to read a file with spaces in C++?

I started having C++ classes at university last week. At the moment I just know some C language which makes me a little confused when learning C++. I have this exercise that says:
"Write and use the fstream library to read a text file. The function should write on the screen each text line read of the file (with spaces)."
I wrote the code below that can write the line but without spaces. I've also heard about getline, but I don't know how to use it, the compiler allways says "no matching function for call to getline".
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
file_read(){
ifstream origem;
origem.open("ficheiro.txt");
if (!origem) {
cerr << "Error" << endl;
return -1;
}
char outp[100];
while(!origem.eof() ){
origem >> outp;
cout << outp;
}
return 0;
}
For example: If i have in the ficcheiro.txt"My dog has a bone", the programm will write it like "Mydoghasabone"
So with the getline I tried this:
...
ifstream origem;
origem.open("ficheiro.txt");
if (!origem) {
cerr << "Error" << endl;
return -1;
}
char outp[100];
getline(origem, outp);
origem >> outp;
cout << outp;
return 0;
}
The compiler said:[Error] no matching function for call to 'getline(std::ifstream&, std::char [100])'
My problem is just to read the file including the spaces!
I'm also having some trouble learning C++, I started learning 'Classes' and using the CMD and I don't even know what I'm learning. Do you know where can I learn C++ in a more understandable way?
Try this
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int file_read()
{
ifstream origem;
origem.open("ficheiro.txt");
if (!origem) {
cerr << "Error" << endl;
return -1;
}
char outp[100];
while( origem.getline(outp,100) )
cout << outp;
return 0;
}
int main()
{
file_read();
}
The compiler said:[Error] no matching function for call to 'getline(std::ifstream&, std::char [100])'
if you want to use getline() change outp from char to string like
string outp;
while( getline(origem,outp))
cout << outp;
Because getline() is for string.

Read all character including the null byte

I want to read out the chrome history from its file. I want to get all characters and null byte that's in that file. The problem I'm facing is that I only get some part of the text that's in the file. I belive it stop due to a null byte or a speical character.
HereĀ“s my code that I have at the moment.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main(){
string str;
std::ifstream in("c:/Users/Petrus/Documents/History"); // I have copy my file into my documents to make sure I'm not interfering with Chrome.
std::stringstream buffer;
if (!in.is_open()){
cout << "Failed to open" << endl;
}
else{
cout << "Opened OK" << endl;
}
buffer << in.rdbuf();
std::string contents(buffer.str());
while (getline(buffer, str))
{
cout << str;
}
in.close();
system("PAUSE");
return 0;
}
If you want to take a look at the chrome history file its located at:
C:\Users\YOUR NAME\AppData\Local\Google\Chrome\User Data\Default -->History
(PS You have to include hidden files to be able to see Appdata.)
Thanks in advance
std::getline() should be used only to read plain text files.
To read arbitrary binary files you should use read(). Additionally, on your operating system you must open binary files using the std::ios::binary flag.

I would like to know why my reading of the file is stopping early

I'm a beginner C++ user and I have tried collaborating with my classmates and such but we haven't been able to find an answer to this question. Our instructor has provided us with a linker that runs the main function for us and provides a simple text file for us to read from, and for the time being the second const char* in the heading is unimportant, for now all I need is to read the data from the file const char* saifFile and display it on-screen. When I run my program I have found that it stops the reading early. And I understand that you may not be able to help because you do not have access to the linker, but any help would be much appreciated.
Here is all my code:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
const int DESC_SIZE = 37;
struct Item
{
int itemId;
char description[DESC_SIZE];
double cost, price;
};
int processFile(const char* saifFile, const char* raofFile)
{
fstream outFile, inFile;
Item Inventory;
inFile.open(saifFile, ios::in);
while (inFile)
{
inFile >> Inventory.itemId >> Inventory.cost >> Inventory.price;
inFile.getline(Inventory.description, DESC_SIZE);
cout << " " << Inventory.itemId << " " << setw(5) << Inventory.cost << " " << setw(5) << Inventory.price <<" " << Inventory.description << endl;
}
return 0;
}
Make sure that the data type you have set to receive from inFile matches the type that inFile reads. If not, you will get a stream error and that will cause your program to stop reading.
After every read, try to inFile.clear() and see if your program hangs or stops early. Alternatively, after each read try
if(inFile.fail())
{
cout << "Read error in file\n";
}
This may not be the answer, but I'd start debugging here.
Try changing the while statement to:
while(!inFile.eof())
And also make sure that you have stored the data in the file in proper order.

Printing out blank spaces from a text file in C++

#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <string>
#include <iomanip>
#include <fstream>
#include <stdio.h>
using namespace std;
int main()
{
ifstream file;
string filename;
char character;
int letters[153] = {};
cout << "Enter text file name: ";
cin >> filename;
file.open(filename.c_str());
if (! file.is_open())
{
cout << "Error opening file. Check file name. Exiting program." << endl;
exit(0);
}
while (file.peek() != EOF)
{
file >> character;
if(!file.fail())
{
letters[static_cast<int>(character)]++;
}
}
for (int i = 0; i <= 153; i++)
{
if (letters[i] > 0)
{
cout << static_cast<char>(i) << " " << letters[i] << endl;
}
}
exit(0);
}
#endif
Hi everyone, my current code counts the frequency of each letter from a text file. However, it does not count the number of blank spaces. Is there a simple way to printout the number of blank spaces in a .txt file?
Also, how come when I'm trying to access a vector item, I run into a seg fault?
For example, if I use:
cout << " " + letters[i] << endl;, it displays a segfault. Any ideas?
Thank you so much.
By default, iostreams formatted input extraction operations (those using >>) skip past all whitespace characters to get to the first non-whitespace character. Perhaps surprisingly, this includes the extraction operator for char. In order to consider whitespace characters as characters to be processed as usual, you should alter use the noskipws manipulator before processing:
file << std::noskipws;
Don't forget to set it back on later:
file << std::skipws;
What if you're one of those crazy people who wants to make a function that leaves this aspect (or in even all aspects) of the stream state as it was before it exits? Naturally, C++ provides a discouragingly ugly way to achieve this:
std::ios_base::fmtflags old_fmt = file.flags();
file << std::noskipws;
... // Do your thang
file.flags(old_fmt);
I'm only posting this as an alternative way of doing what you're apparently trying. This uses the same lookup table approach you use in your code, but uses an istreambuf_iterator for slurping unformatted (and unfiltered) raw characters out of the stream buffer directly.
#include <iostream>
#include <fstream>
#include <iterator>
#include <climits>
int main(int argc, char *argv[])
{
if (argc < 2)
return EXIT_FAILURE;
std::ifstream inf(argv[1]);
std::istreambuf_iterator<char> it_inf(inf), it_eof;
unsigned int arr[1 << CHAR_BIT] = {};
std::for_each(it_inf, it_eof,
[&arr](char c){ ++arr[static_cast<unsigned int>(c)];});
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);++i)
{
if (std::isprint(i) && arr[i])
std::cout << static_cast<char>(i) << ':' << arr[i] << std::endl;
}
return 0;
}
Executing this on the very source code file itself, (i.e. the code above) generates the following:
:124
#:4
&:3
':2
(:13
):13
*:1
+:4
,:4
/:1
0:3
1:2
2:1
::13
;:10
<:19
=:2
>:7
A:2
B:1
C:1
E:2
F:1
H:1
I:3
L:1
R:2
T:2
U:1
X:1
[:8
]:8
_:10
a:27
b:1
c:19
d:13
e:20
f:15
g:6
h:5
i:42
l:6
m:6
n:22
o:10
p:1
r:37
s:20
t:34
u:10
v:2
z:2
{:4
}:4
Just a different way to do it, but hopefully it is clear that usually the C++ standard library offers up elegant ways to do what you desire if you dig deep enough to find whats in there. Wishing you good luck.

Writing using << on an fstream

I'm trying to write a long to a text file using c++ fstream class. The file is already created on disk before the execution. I run the following code and can read the initial value but can't save the new one, overwriting. What am i doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
long f;
fstream myFile("data.txt", fstream::in|fstream::out);
cout << "f before: " << f << endl;
myFile >> f;
cout << "f after: " << f << endl;
f++;
cout << "f after increment: " << f << endl;
myFile << f;
myFile.close();
return 0;
}
After that, I read the value in the file and it isn't changed. What I did wrong here?
You need to rewind to the beginning of the file before writing. Otherwise the second value is written after the first one.
You need to add myFile.seekp(ios::beg); just before myFile << f; in order to update the count correctly.
If you want to keep appending to the end, add myFile.clear(); before myFile << f;. This will cause the contents to become :
1->12->1213->12131214->1213121412131215. This is required because eof is reached upon reading the input. Note that get and put pointers are the same.
As you have yourself correctly pointed out, this is required because the file has just the number, not even the newline. Thus the read operation hits straight the EOF and causes problems. To work around it, we clear eof status and continue.
Adding a newline at the end is a solution as you suggested. In that case
myFile.seekp(ios::beg);
myFile << f<<"\n";
Would be the complete solution.
I figured what I was doing wrong here:
My file contained ONLY the long that I wanted to read and write afterwards. When I read the file, I reached EOF and then couldn't rewind or write anything at the end.
That said, my solution was to include a space or a \n at the end of the file.
Does anyone know why the API works this way? Does not seeem very useful for me...
It has to do with this line:
myFile >> f;
Remove it and everything works just fine. I'm not familiar with fstream but it seems to me this code would try to force a string in a long. I'm also not allowed to cast it to a long, which makes me think this is never meant to be executed like this. I suggest you read up on how to retrieve a value from a file as a long type and then try again.
edit:
After reading a bit this site suggested you have to close and reopen the file between reading and writing, I was amazed that actually fixed it. I can't help but wonder why though, I thought fstream was meant for reading OR writing OR both.... Anyway, here is your working code:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
long f;
fstream myFile("data.txt", fstream::in|fstream::out);
cout << "f before: " << f << endl;
myFile >> f;
cout << "f after: " << f << endl;
f++;
cout << "f after increment: " << f << endl;
myFile.close();
myFile.open("data.txt", fstream::in|fstream::out);
myFile << f;
myFile.close();
return 0;
}