Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

UNIX file redirection (programming for) 1

Status
Not open for further replies.

Cake

Programmer
Oct 22, 2000
12
0
0
US
Hello everyone,
I need to know how to code a program so that it will accept redirection. This program is supposed to accept a list of numbers and store them in variables for later use in the program. When putting numbers in on the command line as arguments, it works fine... but as soon as I type this on the command line -

myprog.exe < data.txt

- I get a stack dump. data.txt contains numbers separated by spaces and line feeds, and myprog.exe is the compiled prog. I use argc and argv[], and I run into stack dumps with the redirection.

I need to make my program understand how to accept input from redirection. And the catch here is - *without* using file functions, using only redirection.

Maybe if someone has a simple and short sample code laying around similar to this, could you post it?

Any comments, ideas, or anything else are welcome.

Thanks,
Cake. [sig][/sig]
 
#include <stdio.h>

int main () {
int x, i = 1;
while (scanf(&quot;%d&quot;, &x) != EOF)
printf (&quot;%d: %d\n&quot;, i++, x);
} [sig][/sig]
 
Perhaps following sentence may work

cat data.txt|myprog.exe

[sig]<p>hnd<br><a href=mailto:hasso55@yahoo.com>hasso55@yahoo.com</a><br><a href= > </a><br> [/sig]
 
Ok thanks, very good info...

Does scanf() work if I want to detect line feeds? Or does it strip them out? What would I use to detect line feeds?

Cake. [sig][/sig]
 
Code:
#include <stdio.h>

int main () {
  int x, lin = 0, col = 0;
  char tmp_ch;
  while (scanf(&quot;%d&quot;, &x) != EOF) {
    printf (&quot;(lin=%d,col=%d): %d\n&quot;, lin, col++, x);
    scanf (&quot;%*[ \t\r]&quot;); /* skipping whitespaces and CRs */
    /* unfortunately scanf doesn't count void (that is %*) conversions, 
     so scanf (&quot;%*1[\n]&quot;) is always 0. */
    while (scanf (&quot;%1[\n]&quot;, &tmp_ch) == 1) { /* instead you could use getc and ungetc */
      lin++; col=0;
      scanf (&quot;%*[ \t\r]&quot;);
    }
  }
  printf (&quot;Number of lines: %d\n&quot;, lin);
}
[sig][/sig]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top