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);

        cout<<"Error opening file."<<endl;
        return 1;

    line = new char[width];

    while(!infile.eof() && sCounter < stop)
        line[counter] = infile.get();


        if(counter == width)
            Dump(line, width);
            counter = 0;

    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)

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:

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.

<title>well come to home page</title>
<table cellpadding=2 width=100% border=2 >

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


Be a part of the DaniWeb community

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