1

I have to do an assignment where I have to write a C-Programm, where it gets the input-file-name from the console as command line parameter.
It should move the data from the input.txt file (the input file has the information for the bmp file - color etc.) to the generated output.png file. The 20 20 parameters stand for width and height for the output.png image.

So the console-request for example (tested on Linux) will look like this:

./main input.txt output.bmp 20 20

I know that this code reads an input.txt File and puts it on the screen.

FILE *input;
int ch;
input = fopen("input.txt","r");
ch = fgetc(input);
while(!feof(input)) {
    putchar(ch);
    ch = fgetc(input);
}
fclose(input);

And this would (for example) write it to the output.png file.

FILE *output;
int i;
     output = fopen("ass2_everyinformationin.bmp", "wb+"); 
 for( i = 0; i < 55; i++)               
 {
     fputc(rectangle_bmp[i], output);
 }
 fclose(output);

But this code works only, if I hard-code the name directly in the code, not by using a command line parameters.
I don't have any clue, how to implement that and I also didn't find any helpful information in the internet, maybe someone can help me.

Greetings

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
s.r.
  • 146
  • 8
  • 1
    https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – Mat Nov 28 '17 at 15:27
  • Are you aware of the parameters to main()? I.e. argc and argv. – Yunnosch Nov 28 '17 at 15:58
  • @Yunnosch no i am not.. do I need them get the wanted result? – s.r. Nov 28 '17 at 16:03
  • Without using them it will be hard, with using them easy. One tells you how many arguments your program got, the other represents an array providing them as "strings". Find a tutorial which does not start with `int main()` or `int main(void)`. – Yunnosch Nov 28 '17 at 16:05
  • thanks a lot for that tipp! Do you know a good (and easy) turorial by any chance? – s.r. Nov 28 '17 at 16:09

1 Answers1

0

The full prototype for a standard main() is

int main(int argc, char* argv[]);

You get an int with the number of arguments, argc and
a list of "strings" (as far as they exist in C), argv.

You can for example use

#include "stdio.h"
int main(int argc, char* argv[])
{

    printf("Number: %d\n", argc);
    printf("0: %s\n", argv[0]);
    if (1<argc)
    {
        printf("1: %s\n", argv[1]);
    }
}

to start playing with the arguments.

Note that this is intentionally not implementing anything but a basic example of using command line parameters. This matches an accpeted StackOverflow policy of providing help with assignments, without going anywhere near solving them.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54