tags:

views:

90

answers:

1

I'm using XCode and I'm trying to open a file that gets passed as a command line argument, and output the number of lines that gets passed as a command line argument of that file, to the console in C. In XCode, my arguments are "test.rtf", and "5". My rtf looks like:

line 1 test
line 2 test
line 3 test
line 4 test
line 5 test
line 6 test
line 7 test
line 8 test
line 9 test
line 10 test

I have tried this with my rtf in the same folder as my XCode project folder, and in the Debug folder where the executable is. My code is:

#include <stdio.h>
#include <stdlib.h>
#define CORRECT_PARAMETERS 2
int main(int argc, char *argv[])
{
 int x;
 if (argc != CORRECT_PARAMETERS) {
  printf("Wrong number of parameters inputted.");
 }
 else {
  FILE *inFp;             /*declare a file pointer */
  if ((inFp = fopen(argv[0], "r") == NULL)) {
   fprintf(stderr, "Can't open file");
   exit(EXIT_FAILURE);
  }
  else {
   for (x = 1; x <= argv[1]; x++) {
    while ((x = fgetc(inFp)) != EOF) {
      printf("%c", x);
    }
   }
  }
  fclose(inFp);
 }

}

I know my code may not be correct of outputting the number of lines input at the command line, but I cannot get the beginning part working of just opening the file. What gets outputted is:

Wrong number of parameters inputted.

Thanks!

+9  A: 

In XCode, my arguments are "test.rtf", and "5".

Well, then argc will take the value of 3.

argv[0] : name of the program

argv[1]: "test.rtf"

argv[2]: 5

You should update your defined constant to take the value of 3.

 if ((inFp = fopen(argv[0], "r") == NULL))

argv[0] is the name of the program being executed.

What you are looking for (first argument) is argv[1]

int x;
for (x = 1; x <= argv[1]; x++) {

This smells like trouble. You are comparing a c-string to an integer. Try this (including using argument 2 rather than 1, as mentioned above):

int x;
int limit = atoi(argv[2]);
for (x = 1; x <= limit; x++)

Here you are changing the value of X.

 while ((x = fgetc(inFp)) != EOF)

The assignment x=1 only happens once !!!. Read inFp into another variable.

Tom
Not to mention that the for loop tests `x` and yet the while loop within always ensures `x = EOF` before the condition part of the loop is tested. So depending on the definition of `EOF` the for loop will either run once and terminate or it will loop infinitely.
PP
Good answer, @Tom. +1 - but I fixed limit assignment to use argv[2] instead of argv[1] (something you'd already mentioned but hadn't caught this instance of).
paxdiablo