3

I have a c++ program which has some command line options. One of them is the file name. The file size is big so I decided to compress it and then try to find a way that the c++ program read the compressed file instead of the plain text file.

According to what is stated here How to read a .gz file line-by-line in C++? I tried the second answer but it doesn't work.

Assume the normal command line for running my program is

 ./run 1 file.txt 10

Now I run

 zcat file.gz | ./run 1 file.gz 10

But the output is invalid. How can I fix that?

P.S:

The file looks like

10 1000
2   39
45 124

And the code which reads the file looks like

char *inp = argv[2];
std::ifstream fin (inp);
int a, b;
while (fin >> a >> b ) {
   // somthing
}
Community
  • 1
  • 1
mahmood
  • 23,197
  • 49
  • 147
  • 242
  • 1
    Can you change your program so it reads from STDIN instead of opening the given file name? – jogojapan Jun 20 '13 at 07:12
  • What do you mean? Using STDIN, I have to enter the input interactively. Right? Please see the updated post – mahmood Jun 20 '13 at 07:17
  • `zcat` generates output on its STDOUT. The pipe `|` forwards this to the STDIN of your process. That's what pipes do. – jogojapan Jun 20 '13 at 07:18
  • ok I understand. So how can I change the program to meet that need? Can you post a reply? – mahmood Jun 20 '13 at 07:19

1 Answers1

2

The simplest immediate fix in your situation is to change this:

char *inp = argv[2];
std::ifstream fin (inp);
int a, b;
while (fin >> a >> b ) {
  // something
}

into this:

char *inp = argv[2];
int a, b;
while (std::cin >> a >> b ) {
  // something
}

I've replaced fin with std::cin. You need to #include <iostream> for this if you haven't done so yet.

This will read from STDIN, which is where the pipe | sends the output of zcat.

If you want to keep both versions – one that reads from file and one that reads from STDIN – you could use a command line argument to indicate that you are reading from STDIN, and then have an if-clause in the code to distinguish between the two usages.

jogojapan
  • 68,383
  • 11
  • 101
  • 131