tags:

views:

199

answers:

1

This is a simple code that open and print the file content.

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

int main  ( int arg_count, char *arg_vec[] ) {
    int ch;
    FILE * fp;
    int i;

    if (arg_count <2) {
        printf("Usage: %s filename\n", arg_vec[0]);
        exit(1);
    }

    if ((fp = fopen(arg_vec[1], "r")) == NULL) { // can't open file

        printf("Can't open %s \n", arg_vec[1]);
        exit(1);
    }

    for (i = 1; i <(arg_count+1); i++) {
         printf("%s \n\n", arg_vec[i]); // print file name

         while ((ch = getc(fp)) != EOF) {
             putc(ch,stdout); // print content
         }
    }

    fclose(fp);

    return 0;
}

But why it gives (null) at the end of it's output printout:

Filename.txt

text
text
(null)
+3  A: 

You're looping one to many times because of arg_count+1. The null is because you're trying to print a filename that does not exist in the argument list. You also need to open and close for each file in your list.

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

int main  ( int arg_count, char *arg_vec[] ) {
    int ch;
    FILE * fp;
    int i;

    if (arg_count < 2) {
        printf("Usage: %s filename\n", arg_vec[0]);
        exit(1);
    }

    for (i = 1; i < arg_count; i++) {
         printf("File: %s \n\n", arg_vec[i]); // print file name
         if ((fp = fopen(arg_vec[i], "r")) == NULL) { // can't open file
            printf("Can't open %s \n", arg_vec[i]);
            exit(1);
         }

         while ((ch = getc(fp)) != EOF) {
             putc(ch,stdout); // print content
         }
         fclose(fp);
    }

    return 0;
}
RC