Search code examples
cfilesystemsfile-manipulation

a program that takes one command line argument and outputs the contents of the file to standard out.


I was assigned a program to write that uses file system calls to take a command line argument(assuming you pass in a text file address) and return the contents of said file. I have this code so far, but can't seem to figure out why my compiler is giving me errors in terms of recognizing the text-file passed as an argument, along with printing the information received from the file. Any sort of assistance/help is greatly appreciated.

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>



int main(int argc, char *argv[]){




int FP;
ssize_t bytes;

char buffer [100];

if(argc == 1){

FP = open(argv[1], O_RDONLY);
printf("Program name is : %s", argv[0])
bytes = read(FP, buffer,sizeof(buffer) -1);
printf("%s", bytes);
close(FP);

}






return 0;


}

Solution

  • the following proposed code:

    1. incorporates the comments to the question
    2. implements the desired functionality
    3. proper checks for errors
    4. documents why the header files are being included. In general, if you cannot state why a header file is being included, then don't include it. (the compiler will then tell you if you actually need that header file, and why
    5. when compiling always enable the warnings, then fix those warnings. (for gcc, at a minimum use: -Wall -Wextra -pedantic -Wconversion -std=gnu11 )

    and now, the proposed code.

    #include <stdio.h>   // fopen(), perror(), fgets(), fprintf(), printf(), FILE
    #include <stdlib.h>  // exit(), EXIT_FAILURE
    
    
    #define MAX_INPUT_LEN 100
    
    int main(int argc, char *argv[])
    {
        FILE *fp;
        char buffer [ MAX_INPUT_LEN ];
    
        if(argc != 2)
        {
            fprintf( stderr, "USAGE: %s fileName\n", argv[0] );
            exit( EXIT_FAILURE );
        }
    
        // implied else, correct number of command line parameters
    
        printf( "Program name is : %s", argv[0] );
        printf( "file to read: %s\n", argv[1] );
    
        fp = fopen( argv[1], "r" );
        if( NULL == fp )
        {
            perror( "fopen failed" );
            exit( EXIT_FAILURE );
        }
    
        // implied else, fopen successful
    
        while( NULL != fgets( buffer, sizeof buffer, fp ) )
        {
            printf( "%s", buffer );
        }
    
        fclose( fp );
    
        return 0;
    }