Reputation: 13
Basically this program is trying to implement a simple C version of the UNIX cat command. It will only display one file and if done correctly it should be able to execute on the command line with a single command line argument consisting of the name of what needs to be displayed. Some of the questions I have tried to look at as a reference are "How to continuously write to a file with user input? C language", "Create File From User Input", and "Fully opening a file in c language". These, however, did not help me very much since one wanted to open a file when it was selected with a cursor, the other was in another language, and the final one was a bit hard to follow since I'm not at that level yet. Below is my code thus far and if you all are able to lend me any advice I'd greatly appreciate it!
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 30
int main (int argc, char** argv)
{
File *stream;
char filename[MAX_LEN];
printf("File Name: ");
scanf("%s", filename);
stream = fopen(filename, "r");
while(1)
{
fgets(stream);
if(!feof(stream))
{
printf("%s", "The file you entered could not be opened\n");
break;
}
}
printf("To continue press a key...\n");
getchar();
fclose(stream);
return 0;
}
Upvotes: 0
Views: 16944
Reputation: 457
If your aim is to re-code the cat function under Linux, this code serve your purpose using open, close and read system calls under Linux.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#define BUFFER_SIZE 50
int main(int argc, char **argv)
{
int file;
char buffer[BUFFER_SIZE];
int read_size;
if (argc < 2)
{
fprintf(stderr, "Error: usage: ./cat filename\n");
return (-1);
}
file = open(argv[1], O_RDONLY);
if (file == -1)
{
fprintf(stderr, "Error: %s: file not found\n", argv[1]);
return (-1);
}
while ((read_size = read(file, buffer, BUFFER_SIZE)) > 0)
write(1, &buffer, read_size);
close(file);
return (0);
}
In this piece of code, you can see that error checking is done by verifying that system calls won't return -1 (under linux, system calls usually return -1 in case of error).
Hope it can help you
Upvotes: 2