Hi, I copied one file into another but couldn't figure out how I would number the lines and put a heading on chem.lis, which is the output.

here is the program i wrote so far


int main(int argc, char *argv[])
  FILE *inp, *outp;
  char ch;

 argv[1] = "chem.out";
 argv[2] = "chem.lis";

 inp = fopen(argv[1], "r");
 if(inp == NULL)
   printf("\nCannot open file %s for for output\n", argv[2]);
 outp = fopen(argv[2], "w");
 if(outp == NULL)
  printf("\nCannot open file %s for output\n", argv[2]);

  for(ch = getc(inp); ch !=EOF; ch = getc(inp))
    putc(ch, outp);

  printf("\nCopied %s to %s\n", argv[1], argv[2]);

  return 0;


it should look like this
************** chem.out ***************
1 1 Hydrogen H 1.01
2 11 Sodium Na 22.99
3 20 Calcium Ca 40.08
4 50 Tin Sn 118.69
5 84 Polonium Po 209.00
6 88 Radium 88 226.03

but right now it's
1 Hydrogen H 1.01
1 Hydrogen H 1.01
1 Hydrogen H 1.01
50 Tin Sn 118.69
84 Polonium Po 209
88 Radium Ra 226.03

so, how should i go about doing so?

Recommended Answers

All 3 Replies

You need to count how many lines there are.

Every time you read '\n' from the file, increment your current line number and print it to the file.

Hope this helps.

if i do something like this, it messes up the output

for(ch = getc(inp); ch !=EOF; ch = getc(inp))
    if(getc(inp) == '\n') 
       fprintf(outp,"\n%d ", i);   
    putc(ch, outp);

Please use code tags.

Think about why that messes up and you'll be able to fix it easily. You are on the right track.

Also, there is a special case for the very first line.

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.