简体   繁体   中英

output to a file using command line

I am writing a program that should be able to take command line parameters. Basically, the user must be able to specify a file name through command prompt while calling the program. ie the program should be able to take in a parameter like: doCalculation -myOutputfile.txt. where doCalculation is the name of my program and myOutputfile is the file I want my results written to (ie output the results of my calculations to the specified file name).

So far I can call my function through the command prompt. I am not sure how to get my program to write to the filename specified (or create this file if it does not exist already).

My code is as follows:

int main(int argc, char *argv[])
{
    FILE* outputFile;
    char filename;

    // this is to make sure the code works
    int i = 0;
    for (i = 0; i < argc; i++) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }

    //open the specified file
    filename= argv[i];   
    outputFile = fopen("filename", "r");

    //write to file
    fclose(outputFile);
}

So a couple things I noticed...

  1. If you want to write to the file, use "w" for write-mode instead of "r" for read-mode when opening the file.
  2. You declared filename as a single character rather than a pointer to a string (char *). Making it a pointer will allow filenames with a length > 1 (array of chars rather than a single char).
  3. As Ashwin Mukhija mentioned, you're using i after the for loop set it to 2, when infact you want the 2nd (index 1) argument.
  4. You had the filename argument in the open() function as a literal "filename" rather than your filename variable.

See if this code helps solve your problem, (I also tossed a fprintf() in there to show you how you can write to the file). Cheers!

int main(int argc, char *argv[])
{
    FILE* outputFile;
    char* filename;

    // this is to make sure the code works
    int i = 0;
    for (i = 0; i < argc; i++) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }

    //saftey check
    if(argv[1])
    {
        filename = argv[1];

        //open the specified file
        outputFile = fopen(filename, "w");

        fprintf(outputFile, "blah blah");

        //write to file
        fclose(outputFile );
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM