paulscalzojr13
paulscalzojr13

Reputation: 1

Open two arguments from command line in C

How would I go about opening only two files from the command line in C? I am working on a Machine Learning Project where the first file has the training data (train.txt) and the second file has the actual data (data.txt). For example, when I compile I am looking for something like this:

./machineLearning train.txt data.txt

Initially, I was thinking it would be something along these lines but was not quite sure if this made sense:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    char fileName[100];

    while(argc < 2)
    {
        FILE* fp;
        fp = fopen(fileName, "r"); 
    }
}

Upvotes: 0

Views: 136

Answers (1)

JayK
JayK

Reputation: 3141

You find the command line arguments in argv. The first argument is a string at argv[1] and the second at argv[2]. So (after checking argc that you have indeed gotten two arguments), just pass these strings to fopen to open the files:

#include <stdio.h>

int main(int argc, char *argv[])
{
    FILE *file1;
    FILE *file2;
    if (argc < 3) {
        /* report that not enough arguments have been given and exit */
    }
    file1 = fopen(argv[1], "r");
    file2 = fopen(argv[2], "r");
    /* Check whether file1 or file2 are 0, in case either file could not be opened,
       then use the file streams as you require. */
}

Upvotes: 2

Related Questions