I have a simple program that is suppose to read character by character from a file, then if a counter reached a certain limit, it will print those characters in hex format and continue reading the next character from file:
Here is my code, but it isnt working correctly, instead of continuing to read the nex line in the file, it just stops.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int ReadFile(string fname, int width, int stop);
void Dump(string line, int width);
int main(int argc, char *argv[])
{
if(argc != 4)
{
cout<<"Usage: [filename] [width] [stop]"<<endl;
return 1;
}
cout<<"File name: "<<argv[1]<<endl;
cout<<"Width: "<<atoi(argv[2])<<endl;
cout<<"Stop: "<<atoi(argv[3])<<endl;
ReadFile(argv[1], atoi(argv[2]), atoi(argv[3]));
return 0;
}
int ReadFile(string fname, int width, int stop)
{
int counter = 0;
int sCounter = 0;
char *line;
ifstream infile(fname);
if(!infile)
{
cout<<"Error opening file."<<endl;
return 1;
}
line = new char[width];
while(!infile.eof() && sCounter < stop)
{
line[counter] = infile.get();
counter++;
sCounter++;
if(counter == width)
{
Dump(line, width);
counter = 0;
}
}
infile.close();
delete[] line;
return 0;
}
void Dump(string line, int width)
{
for(int i = 0; i < width; i++)
{
cout<<hex<<(int)line[i]<<" ";
}
cout<<" : ";
for(int i = 0; i < width; i++)
{
if(line[i] <= 32)
cout<<".";
else
cout<<line[i];
}
cout<<endl;
}
So how do I fix it?