Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

Read input.txt file and also output.bmp file from terminal (C-programming)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", argc);
    printf("0: %s
", argv[0]);
    if (1<argc)
    {
        printf("1: %s
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...