开发者

Unix Command Line Parameter Help

开发者 https://www.devze.com 2023-04-05 00:45 出处:网络
I am currently trying to read in an input file of 15,000 integers and pass these values into an array. I\'m really rusty when it comes to passing command line arguments into the program, so perhaps I

I am currently trying to read in an input file of 15,000 integers and pass these values into an array. I'm really rusty when it comes to passing command line arguments into the program, so perhaps I am not doing this the correct way. Here is what I have coded thus far:

#include <stdio.h>

int main(int argc, char *argv[]) {
int i;
FILE *fp;
int c;
int values[15000];
char line[32];
int index = 0;

for (i = 1; i < argc; i++) {
    fp = fopen(argv[i], "r");

    if (fp == NULL) {
        printf(stderr, "cat: can't open %s\n", argv[i]);
        continue;
    }

    while (fgets(line, sizeof(line), fp) != NULL) {
        scanf(line, "%d", values[index];
        index++;
    }

    fclose(fp);
}

retur开发者_如何转开发n 0;
}

I am invoking gcc -o prob_5 input.txt from the command line and am receiving this error message:

/usr/bin/ld:input.txt: file format not recognized; treating as linker script
/usr/bin/ld:input.txt: syntax error
collect2: ld returned 1 exit status

Is there an error with my code or the command line arguments, or both?


Try

gcc -o prob5 prob5.c
./prob5 input.txt

Assuming that the source file (shown...) is named prob5.c - you don't mention that :)

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;
    FILE *fp;
    int values[15000];
    char line[32];
    int index = 0;

    for (i = 1; i < argc; i++)
    {
        fp = fopen(argv[i], "r");

        if (fp == NULL)
        {
            fprintf(stderr, "cat: can't open %s\n", argv[i]);
            continue;
        }

        while (fgets(line, sizeof(line), fp) != NULL && (index < 15000))
        {
            sscanf(line, "%d", &values[index]);
            index++;
        }

        fclose(fp);
    }

    return 0;
}


You need to compile the source code

gcc prob_5.c -o prob_5

and then run the binary with command-line parameters

./prob_5 input.txt

What happens with what you're doing is the compiler trying to interpret a bunch of numbers as source code.


The problem is your execution. gcc is a compiler/linker and you shouldn't pass in your input files:

gcc -o prob_5 prob_5.c
./prob_5 input.txt
0

精彩评论

暂无评论...
验证码 换一张
取 消