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;
}
the following proposed code:
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;
}