C++ Program, convert regular file to hexadecimal and binary - c++

My HexDump that I have takes a file and outputs the ASCII hex value of that file, and also the binary values of that file. In example, when I run my program on a text file containing "Hello World!", I get
4865 6C6C 6F20 etc. So I know it is converting the direct ascii characters to the correct hex values. But, an example in my program syllabus shows that other bytes should be printed before the text.
This leads me to believe that I am not reading the entire file correctly. I think I may need to use fread() or fopen()? Please help me out. I am a C++ beginner. This is my code that I run on my txt file:
#include <iostream>
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <bitset>
using namespace std;
string stringToHexOrByte(char input, bool toByte)
{
string output;
if (toByte) {
bitset<8> temp(input);
output = temp.to_string();
}
else {
static const char hex_digits[] = "0123456789ABCDEF";
output.reserve(2);
output.push_back(hex_digits[input >> 4]);
output.push_back(hex_digits[input & 15]);
}
return output;
}
int main(int argc, char* argv[]) {
// Create a text string, which is used to output the text file
string initialInput;
// char variable in order to read char by char from file
char myChar;
//bool value to know if we have the byte parameter called
bool byteOption;
// string which will retain the converted char to hex or byte
string convChar;
string fileName;
//Check if we have -b byte Option
if (argc > 2) {
byteOption = true;
fileName = argv[2];
}
else {
byteOption = false;
fileName = argv[1];
}
// Read from the text file
fstream myFile(fileName, fstream::in);
// we will use this group variable to separate the chars printed as in the examples
int group = 1;
while (myFile >> std::noskipws >> myChar) {
// if the bynary option is selected we will print all the chars separetely
if (byteOption) {
group = 0;
}
convChar = stringToHexOrByte(myChar, byteOption);
cout << convChar;
// here we use the group to get the output expected
if (group) {
group = 0;
}
else {
cout << " ";
group = 1;
}
//clear non-printable chars
if ((int)myChar < 32) {
myChar = '.';
}
// Append to input string
initialInput.append(1, myChar);
}
// Close the file
myFile.close();
//print input
cout << " " << initialInput;
return 0;
}

Related

Text file not reading c++ MacOSX

I have an issue with some code I have been working on. I am trying to read the contents of a text file (input.txt) into a variable fileContents. The loop in the code enters, but the program produces no output. Some of the variables are not used, I know about this. What is wrong?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char const *argv[])
{
ifstream input("input.txt");
ofstream output("output.txt"); //init output controller
// new lines will be skipped unless we stop it from happening:
//input.unsetf(std::ios_base::skipws);
// count the newlines with an algorithm specialized for counting:
unsigned line_count = std::count(std::istream_iterator<char>(input),std::istream_iterator<char>(), '\n');
string fileContents = ""; //init message, that will be filled by input.txt
string str; //temp string
while (input >> fileContents)
{
//cout << "loop entered";
cout << fileContents << "\n";
}
//cout << "test" << "\n";
return 0;
}

using sscanf for space delimiter reading from file C++

#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
int main(int argc, char* argv[])
{
ifstream ifile;
char fName[30][30];
long int uTime[30][10];
ifile.open("sync.log");
char ch;
string str = "";
if(ifile.fail())
{
cout<<"Invalid File Name!";
system("pause");
exit(1);
}
int i = 0;
while(!ifile.eof())
{
getline(ifile, str);
cout<<str<<endl;
sscanf(str.c_str(),"%ld %[^\n]",&uTime[i],fName[i]);
i++;
str = "";
}
ifile.close();
system("pause");
cout<<"Output:"<<endl;
for(i = 0 ; i < 2 ; i ++)
{
cout<<uTime[i]<<" ";
cout<<fName[i];
cout<<endl;
}
getch();
return 0;
}
File : sync.log
Format:
1399865017 Test1.txt
1399865017 Test1.txt
so here is my full code and i have sync.log file in root directory where the VC++ saved the projects...
It must be stored like this in array after Reading from File
uTime[0] = 1399865017;
fName[0] = "Test1.txt";
fName[1] = "Test1.txt";
with this above code i am getting
uTime[0] = 0012F6B0 and fName[0] = "Test1.txt"
and i want this uTime[0] = 1399865017;
fName[0] = "Test1.txt";
I think you meant to use:
long int uTime[30];
instead of
long int uTime[30][10];
With that, the line that reads data into uTime and the line that write uTime to cout would make sense.
Given that you have:
long int uTime[30][10];
when you do:
cout << uTime[i] << …
you are printing a pointer to an array of 10 long. That pointer is formatted in hex; that is why you are getting hex output.
You need to fix the sscanf() call — you've got a bogus argument of &uTime[i] there — and the output too. Since it is not clear why uTime is a 2D array, it isn't easy to tell you how to fix it, but the simplest solution would be to drop the [10] from the array definition.

split string into array C++

How do I split an input string using getline(cin, input); to input the variable? I want to split it into a char array like this:
char[] = { // What goes here to make it read the input variable and split it into chars }
Is there any way to do this?
And what about y'all's new posts? Which one is best? Here is the caesar cipher code I need to modify to read the input variable and store its chars in a char array:
// Test Code ONLY
// Not A Commercial Program OR A Crypter
// THIS IS A TEXT CIPHERER
#include <windows.h>
#include <cstdlib>
#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
int main()
{
string in;
string out;
char lower[25] = {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z};
char upper[25] = {A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z};
char upcip[25] = {Z,Y,X,W,V,U,T,S,R,Q,P,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A};
char locip[25] = {z,y,x,w,v,u,t,s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a};
cout << "Enter PlainText: ";
getline(cin, in);
// which sample goes here to read the input var char by char, then store the chars in order in a char array in your opinion?
return 0;
}
A string is already an array of chars:
for (std::string line; std::getline(std::cin, line); )
{
for (std::size_t i = 0, e = line.size(); i != e; ++i)
{
std::cout << "char[" << i << "] = '" << line[i] << "'\n";
}
}
string str;
std::getline(cin,str);
char* pArr = new char[str.size() + 1]; // add 1 for zero element which is the end of string
strcpy(pArr,str.c_str());
/*
some actions with pArr, for ex.
while(*pArr)
std::cout << *pArr; // output string on the screen
*/
// updated: release memory obtained from heap
delete [] pArr;

Removing groups of "000" from my file?

In C++ I have made a program that exports to binary and now I am making a reader. It reads correctly, but there is only 1 issue. My file is a file that contains a set of numbers and when it is read and printed to the screen you see, 1470009300047000199. The sets of 3 "000" isn't supposed to be there. I loaded this file using an ifstream and plan to keep it that way. Can someone tell me how to remove the sets of "000" in my file? If I have to write another C++ program that does that I am fine with it, I just need something to remove the "000" and replace it with a space.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
if (argc < 2)
{
cout << "Error 1";
return 0;
}
else
{
int FileLength;
ifstream InputFile(argv[1], ios::binary);
ofstream OutputFile("DECOMPILED_FILE.txt");
InputFile.seekg(0, ios::end);
FileLength = InputFile.tellg();
InputFile.seekg(0, ios::beg);
for (int i = 0; i < FileLength; i++)
{
cout << InputFile.get();
}
cin.get();
}
return 0;
}
How about a regular expression ? Try finding the substring '000' on the file, if found, replace it by " ".
Pseudocode:
for each line in the file do:
if line.strstr("000") then
line.replace("000", " ")
cout << line << endl;

how to count the characters in a text file

im trying to count the characters inside a text file in c++, this is what i have so far, for some reason im getting 4. even thou i have 123456 characters in it. if i increase or decrease the characters i still get 4, please help and thanks in advance
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const char FileName[] = "text.txt";
int main ()
{
string line;
ifstream inMyStream (FileName);
int c;
if (inMyStream.is_open())
{
while( getline (inMyStream, line)){
cout<<line<<endl;
c++;
}
}
inMyStream.close();
system("pause");
return 0;
}
You're counting the lines.
You should count the characters. change it to:
while( getline ( inMyStream, line ) )
{
cout << line << endl;
c += line.length();
}
There are probably hundreds of ways to do that.
I believe the most efficient is:
inMyStream.seekg(0,std::ios_base::end);
std::ios_base::streampos end_pos = inMyStream.tellg();
return end_pos;
First of all, you have to init a local var, this means:
int c = 0;
instead of
int c;
I think the old and easy to understand way is to use the get() function till the end char EOF
char current_char;
if (inMyStream.is_open())
{
while(inMyStream.get(current_char)){
if(current_char == EOF)
{
break;
}
c++;
}
}
Then c will be the count of the characters
this is how i would approach the problem:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string line;
int sum=0;
ifstream inData ;
inData.open("countletters.txt");
while(!inData.eof())
{
getline(inData,line);
int numofChars= line.length();
for (unsigned int n = 0; n<line.length();n++)
{
if (line.at(n) == ' ')
{
numofChars--;
}
}
sum=numofChars+sum;
}
cout << "Number of characters: "<< sum << endl;
return 0 ;
}
Just use good old C FILE pointers:
int fileLen(std::string fileName)
{
FILE *f = fopen(fileName.c_str(), "rb");
if (f == NULL || ferror(f))
{
if (f)
fclose(f);
return -1;
}
fseek(f, 0, SEEK_END);
int len = fell(f);
fclose(f);
return len;
}
I found out this simple method , hope this helps
while(1)
{
if(txtFile.peek() == -1)
break;
c = txtFile.get();
if(c != txtFile.eof())
noOfChars++;
}
This works for sure, it is designed to read character by character.
It could be easily put into a class and you may apply function for every char, so you may check for '\n', ' ' and so on. Just have some members in your class, where they can be saved, so you may only return 0 and use methods to get what exactly you want.
#include <iostream>
#include <fstream>
#include <string>
unsigned long int count(std::string string)
{
char c;
unsigned long int cc = 0;
std::ifstream FILE;
FILE.open(string);
if (!FILE.fail())
{
while (1)
{
FILE.get(c);
if (FILE.eof()) break;
cc++; //or apply a function to work with this char..eg: analyze(c);
}
FILE.close();
}
else
{
std::cout << "Counter: Failed to open file: " << string << std::endl;
}
return cc;
};
int main()
{
std::cout << count("C:/test/ovecky.txt") << std::endl;
for (;;);
return 0;
}
C++ provides you with a simple set of functions you can use to retrieve the size of stream segment.
In your case, we want to find the file end, which can be done by using fstream::seekg, and providing the fstream::end.
note that fstream is not implementing the end iterator overload, this is it's own end constant
When we've seeked towards the end of the file, we want to get the position of the stream pointer, using tellg (also known as the character count in our case).
But we're not done yet. We need to also set the stream pointer to its original position, otherwise we'll be reading from the end of the file. Something we don't want to do.
So lets call fstream::seekg again, but this time set the position to the begining of the file using fstream::beg
std::ifstream stream(filepath);
//Seek to end of opened file
stream.seekg(0, stream.end);
int size = stream.tellg();
//reset file pointer to the beginning of the file
stream.seekg(0, stream.beg);