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?

Recommended Answers

All 5 Replies

Barring the obvious issue of not properly handling the last span of characters unless they're exactly width length, I don't see any problems. I'd do a few things differently, but the way you're doing it is functional.

Can you provide a sample file as well as an invokation string so that we can see what you're seeing?

Here is a sample:

Hello 
world
this is 3
and 4

The output is nothing

What are you passing as width and stop? So what values do argv[2] and argv[3] have? That's somewhat important in replicating your results. ;)

Sory I took so long to reply, but this is how I run the program.

hexdump.exe TestFile.txt 16 100

The width is how many characters there should be printed on the screen before it prints a newline.
The stop is the total amount of characters to be read from the file.

<html>
<title>well come to home page</title>
<head>
<body>
</body>
<table cellpadding=2 width=100% border=2 >
<tr>
<td>
</td>
</tr>

  • ## Sub-Heading Here ##
    Emphasized Text Here

</table>

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.