2

Well I assume this answer is out there but man is there a flood of people posting the code. I cannot find where it is actually implemented. I am using codeblocks and I am passing the filename into main. But when I click Run, there is no filename that was passed in. How do I pass in a filename in Codeblocks? Do I use cmd promt or what? I want to pass in input.txt but I can't figure it out. Right now to stop it from crashing, I just have it default to input.txt.

nfile = fopen(argv[1], "r+");

    // Check for file open
    if (nfile == NULL) {
        nfile = fopen("input.txt", "r+"); 

        printf("FILE NAME: %s argv\n", argv);

        if (nfile == NULL) {
            printf("Failed to open file. Must have file name (input.txt)\n");
            return -1;
        }
    }
Sean Duggan
  • 1,105
  • 2
  • 18
  • 48
  • possible duplicate of [How to take command line argument in Codeblock 10.05?](http://stackoverflow.com/questions/11888528/how-to-take-command-line-argument-in-codeblock-10-05) – Sean Duggan Nov 25 '14 at 17:08

2 Answers2

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

^ This should be the function header and to use it, you have to use command prompt to pass the argument.

eg: if you are using gcc to compile the program. Then use gcc yourprogram.c

After that use ./a.out input.txt to run the code

MrTambourineMan
  • 1,025
  • 1
  • 11
  • 19
  • Thanks for the help. I still can't figure it out. anyway, does it seem to work? If the filename is passed into main, would this code work? – user2990336 Nov 24 '14 at 20:15
0

Look at the signature for you main procedure. It should look like int main(int argc, char* argv[]). The argc parameter holds the number of arguments including the filename of your program. argv is an array of null-terminated strings holding the arguments. The second one (index 1), if it exists, is likely what you're looking for. What are you getting there?

It looks like you're already using those variables in your code... are you getting a compile error off of them?

To insert the commandline arguments into CodeBlocks, Project > Set programs' arguments... is what you need to access off of the menu.

Sean Duggan
  • 1,105
  • 2
  • 18
  • 48
  • No they are fine. I get all that, I just don't know how to send the string "input.txt" to main when I click run. – user2990336 Nov 24 '14 at 20:10
  • Oh. You're probably invoking this from an IDE if you're clicking "run". Look at your project settings and look for a Command Line Arguments property. Which IDE are you using? – Sean Duggan Nov 24 '14 at 20:14
  • Nevermind. You said CodeBlocks. Editing the answer in. – Sean Duggan Nov 24 '14 at 20:16
  • Ah yes I tried this before even posting. When I click it nothing even happens. Nothing opens nothing changes. Must be something wrong with my installation. – user2990336 Nov 24 '14 at 20:26