linux - C Language Cat Program that Opens File from User Input -


basically program trying implement simple c version of unix cat command. display 1 file , if done correctly should able execute on command line single command line argument consisting of name of needs displayed. of questions have tried @ reference "how continuously write file user input? c language", "create file user input", , "fully opening file in c language". these, however, did not me since 1 wanted open file when selected cursor, other in language, , final 1 bit hard follow since i'm not @ level yet. below code far , if able lend me advice i'd 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 entered not opened\n");             break;         }     }     printf("to continue press key...\n");     getchar();     fclose(stream);     return 0; } 

if aim re-code cat function under linux, code serve purpose using open, close , 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 piece of code, can see error checking done verifying system calls won't return -1 (under linux, system calls return -1 in case of error).

hope can you


Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -