PnP
PnP

Reputation: 3185

Two or more command line arguments?

I've got this code finally working with a single arguement on my command line, i.e. one file for it to work with, although I designed the code with the concept of it working with an unlimited number of files. What it does is take some X number of txt files containing words seperated by spaces, and replaces spaces with \n thus creating a list of words. Though, it successfully completes the first argument, it seg faults when I add two, or three, really want to get this working!

PS. This is a continuation from 2 other posts on the same code. This is not a homework task, I am currently away from Uni, and just experimenting with C file i/o in advance of our lectures.

#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>

int main(int argc, char** argv) {
FILE *fpIn, *fpOut;
int i, j;
j = 1;
int c;
char myString[256];

printf("%d", argc);
printf("\n");
printf("The following arguments were passed to main(): ");
            for(i=1; i<argc; i++) printf("%s ", argv[i]);
printf("\n");

while(argc--) {
    for(i = 1; i <= argc; i++) {
        fpIn = fopen(argv[j], "rb");
        snprintf(myString, 256, "%s~[%d]", argv[j], i);
        fpOut= fopen(myString, "wb");
        while (1) {
            c = fgetc(fpIn);
            if ( c == EOF)
                break;
            if (isspace(c)) 
                c = '\n';
            fputc(c, fpOut );
        }
        j++;
    }
}
return 0;
}

Upvotes: 0

Views: 186

Answers (2)

for(i = 1; i <= argc; i++)

should be

for(i = 1; i < argc; i++)

Yes, I know you are starting from 1, but that is because argv[0] is supposed to be the programs invocation name.

Upvotes: 2

Dan
Dan

Reputation: 10786

It looks like you've got two loops there doing the same thing!

while(argc--) {
for(i = 1; i <= argc; i++) {

You really only need one loop in order to iterate over the arguments. If you use the while loop, then use argc or j as the index to argv. If you use the for loop, which is the neater way, use the for loop argument i as the index to argv.

Upvotes: 2

Related Questions