Read input.txt file and also output.bmp file from

2020-02-02 03:42发布

问题:

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

回答1:

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.