Linux cat command in Cpipe 2 linux commands in CSimple Linux char driverImplementing the 'cat' commandSimple Linux pipelineSize improvements for cat reimplementationVigenère cipher in CLinux C Port Knock ImplementationRecreation of cat in CC Vigenere EncryptorRemoving commented dead code without removing the legitimate comments

Why are 150k or 200k jobs considered good when there are 300k+ births a month?

Do Phineas and Ferb ever actually get busted in real time?

Can I make popcorn with any corn?

How do I create uniquely male characters?

Is it possible to make sharp wind that can cut stuff from afar?

How can the DM most effectively choose 1 out of an odd number of players to be targeted by an attack or effect?

Can I interfere when another PC is about to be attacked?

Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?

Why CLRS example on residual networks does not follows its formula?

Possibly bubble sort algorithm

Motorized valve interfering with button?

What would happen to a modern skyscraper if it rains micro blackholes?

How old can references or sources in a thesis be?

Why has Russell's definition of numbers using equivalence classes been finally abandoned? ( If it has actually been abandoned).

Why Is Death Allowed In the Matrix?

TGV timetables / schedules?

Underlining section titles

Why is an old chain unsafe?

Do any Labour MPs support no-deal?

How to report a triplet of septets in NMR tabulation?

How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?

How to make payment on the internet without leaving a money trail?

Example of a relative pronoun

N.B. ligature in Latex



Linux cat command in C


pipe 2 linux commands in CSimple Linux char driverImplementing the 'cat' commandSimple Linux pipelineSize improvements for cat reimplementationVigenère cipher in CLinux C Port Knock ImplementationRecreation of cat in CC Vigenere EncryptorRemoving commented dead code without removing the legitimate comments






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0












$begingroup$


I wrote my own implementation of the linux cat command in C for my computer laboratory class. We were asked to replicate its functionality with no options passed as arguments or with just the -b, -n and -s options.



I'm posting the code here because, although it works fine, i feel a little bit insecure about. Firstly because i think i "over-coded" it a bit, specially on the option handling part, and also, because i'm still not very confortable working with pointers and so i am not very sure if my approach does not generate memory leaks or malfunctions.



Here it is:



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#define BUF_SIZE 1024

int readStdin(int index, int bflag, int nflag)
char buffer[BUF_SIZE];
while(fgets(buffer, BUF_SIZE, stdin)) //reads from the standard input and prints the input
if (nflag)
printf(" %d %s", index, buffer);
index++;

if (bflag)
if (*buffer == 'n')
printf ("%s", buffer);

else
printf (" %d %s", index, buffer);
index++;


else
printf("%s", buffer);


return index; //returns the incremented index to perpetuate its use


int readFile(char* filename, FILE* fp, int index, int bflag, int nflag)
char ch;
char s[BUF_SIZE];
if (fp==NULL) //in case the file doesn't exist
printf("%s: No such file or directoryn", filename);
exit(1);


if (bflag)
while ((fgets(s,BUF_SIZE,fp)))
if (strcmp(s,"n") == 0)
printf (" %s", s);

else
printf (" %d %s", index, s);
index++;


fclose(fp);

if (nflag)
while ((fgets(s,BUF_SIZE,fp)))
printf (" %d %s", index, s);
index++;

fclose(fp);

else
while ((ch=fgetc(fp)) != EOF) //printing loop
putchar(ch);

fclose(fp);

return index;


void readArgs(int argc, char* argv[])
FILE* fp;
int index = 1; //line index. to be used in case -b or -n is passed as an argument
int option; //option passed as argument
int bflag = 0; //-b option deactivated by default
int nflag = 0; //-n option deactivated by default
opterr = 0; //deactivates getopt's default error messages

//checks if there are options passed as argument and updates their flags
while ((option = getopt(argc, argv, "bn")) != -1)
switch (option)
case 'b':
bflag = 1;
break;
case 'n':
nflag = 1;
break;
case '?': //in case there was some problem
exit(1);



if (bflag == 1 && nflag == 1) //if -b and -n are passed as argument, b overrides n
nflag = 0;


for (int i=optind; i<argc; i++)
if (*argv[i] == '-') //in case of '-' in argv[i], reads from stdin and prints
index = readStdin(index, bflag, nflag);
clearerr(stdin);

else //prints the contents of the file in *argv[i]
fp = fopen(argv[i], "r");
index = readFile(argv[i], fp, index, bflag, nflag);




int main(int argc, char* argv[])
if (argc<2) //if there are no arguments
readStdin(1,0,0);
return 0;

readArgs(argc, argv); //otherwise
return 0;




I didn't implement the -s option because i cant think of a way to handle it at the same time as the other options. That's why i think that the way i am handling the options part is a bit inefficient.



Any suggestions?









share







New contributor




Guilherme Lima is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$


















    0












    $begingroup$


    I wrote my own implementation of the linux cat command in C for my computer laboratory class. We were asked to replicate its functionality with no options passed as arguments or with just the -b, -n and -s options.



    I'm posting the code here because, although it works fine, i feel a little bit insecure about. Firstly because i think i "over-coded" it a bit, specially on the option handling part, and also, because i'm still not very confortable working with pointers and so i am not very sure if my approach does not generate memory leaks or malfunctions.



    Here it is:



    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <ctype.h>
    #define BUF_SIZE 1024

    int readStdin(int index, int bflag, int nflag)
    char buffer[BUF_SIZE];
    while(fgets(buffer, BUF_SIZE, stdin)) //reads from the standard input and prints the input
    if (nflag)
    printf(" %d %s", index, buffer);
    index++;

    if (bflag)
    if (*buffer == 'n')
    printf ("%s", buffer);

    else
    printf (" %d %s", index, buffer);
    index++;


    else
    printf("%s", buffer);


    return index; //returns the incremented index to perpetuate its use


    int readFile(char* filename, FILE* fp, int index, int bflag, int nflag)
    char ch;
    char s[BUF_SIZE];
    if (fp==NULL) //in case the file doesn't exist
    printf("%s: No such file or directoryn", filename);
    exit(1);


    if (bflag)
    while ((fgets(s,BUF_SIZE,fp)))
    if (strcmp(s,"n") == 0)
    printf (" %s", s);

    else
    printf (" %d %s", index, s);
    index++;


    fclose(fp);

    if (nflag)
    while ((fgets(s,BUF_SIZE,fp)))
    printf (" %d %s", index, s);
    index++;

    fclose(fp);

    else
    while ((ch=fgetc(fp)) != EOF) //printing loop
    putchar(ch);

    fclose(fp);

    return index;


    void readArgs(int argc, char* argv[])
    FILE* fp;
    int index = 1; //line index. to be used in case -b or -n is passed as an argument
    int option; //option passed as argument
    int bflag = 0; //-b option deactivated by default
    int nflag = 0; //-n option deactivated by default
    opterr = 0; //deactivates getopt's default error messages

    //checks if there are options passed as argument and updates their flags
    while ((option = getopt(argc, argv, "bn")) != -1)
    switch (option)
    case 'b':
    bflag = 1;
    break;
    case 'n':
    nflag = 1;
    break;
    case '?': //in case there was some problem
    exit(1);



    if (bflag == 1 && nflag == 1) //if -b and -n are passed as argument, b overrides n
    nflag = 0;


    for (int i=optind; i<argc; i++)
    if (*argv[i] == '-') //in case of '-' in argv[i], reads from stdin and prints
    index = readStdin(index, bflag, nflag);
    clearerr(stdin);

    else //prints the contents of the file in *argv[i]
    fp = fopen(argv[i], "r");
    index = readFile(argv[i], fp, index, bflag, nflag);




    int main(int argc, char* argv[])
    if (argc<2) //if there are no arguments
    readStdin(1,0,0);
    return 0;

    readArgs(argc, argv); //otherwise
    return 0;




    I didn't implement the -s option because i cant think of a way to handle it at the same time as the other options. That's why i think that the way i am handling the options part is a bit inefficient.



    Any suggestions?









    share







    New contributor




    Guilherme Lima is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$














      0












      0








      0





      $begingroup$


      I wrote my own implementation of the linux cat command in C for my computer laboratory class. We were asked to replicate its functionality with no options passed as arguments or with just the -b, -n and -s options.



      I'm posting the code here because, although it works fine, i feel a little bit insecure about. Firstly because i think i "over-coded" it a bit, specially on the option handling part, and also, because i'm still not very confortable working with pointers and so i am not very sure if my approach does not generate memory leaks or malfunctions.



      Here it is:



      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      #include <unistd.h>
      #include <ctype.h>
      #define BUF_SIZE 1024

      int readStdin(int index, int bflag, int nflag)
      char buffer[BUF_SIZE];
      while(fgets(buffer, BUF_SIZE, stdin)) //reads from the standard input and prints the input
      if (nflag)
      printf(" %d %s", index, buffer);
      index++;

      if (bflag)
      if (*buffer == 'n')
      printf ("%s", buffer);

      else
      printf (" %d %s", index, buffer);
      index++;


      else
      printf("%s", buffer);


      return index; //returns the incremented index to perpetuate its use


      int readFile(char* filename, FILE* fp, int index, int bflag, int nflag)
      char ch;
      char s[BUF_SIZE];
      if (fp==NULL) //in case the file doesn't exist
      printf("%s: No such file or directoryn", filename);
      exit(1);


      if (bflag)
      while ((fgets(s,BUF_SIZE,fp)))
      if (strcmp(s,"n") == 0)
      printf (" %s", s);

      else
      printf (" %d %s", index, s);
      index++;


      fclose(fp);

      if (nflag)
      while ((fgets(s,BUF_SIZE,fp)))
      printf (" %d %s", index, s);
      index++;

      fclose(fp);

      else
      while ((ch=fgetc(fp)) != EOF) //printing loop
      putchar(ch);

      fclose(fp);

      return index;


      void readArgs(int argc, char* argv[])
      FILE* fp;
      int index = 1; //line index. to be used in case -b or -n is passed as an argument
      int option; //option passed as argument
      int bflag = 0; //-b option deactivated by default
      int nflag = 0; //-n option deactivated by default
      opterr = 0; //deactivates getopt's default error messages

      //checks if there are options passed as argument and updates their flags
      while ((option = getopt(argc, argv, "bn")) != -1)
      switch (option)
      case 'b':
      bflag = 1;
      break;
      case 'n':
      nflag = 1;
      break;
      case '?': //in case there was some problem
      exit(1);



      if (bflag == 1 && nflag == 1) //if -b and -n are passed as argument, b overrides n
      nflag = 0;


      for (int i=optind; i<argc; i++)
      if (*argv[i] == '-') //in case of '-' in argv[i], reads from stdin and prints
      index = readStdin(index, bflag, nflag);
      clearerr(stdin);

      else //prints the contents of the file in *argv[i]
      fp = fopen(argv[i], "r");
      index = readFile(argv[i], fp, index, bflag, nflag);




      int main(int argc, char* argv[])
      if (argc<2) //if there are no arguments
      readStdin(1,0,0);
      return 0;

      readArgs(argc, argv); //otherwise
      return 0;




      I didn't implement the -s option because i cant think of a way to handle it at the same time as the other options. That's why i think that the way i am handling the options part is a bit inefficient.



      Any suggestions?









      share







      New contributor




      Guilherme Lima is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      I wrote my own implementation of the linux cat command in C for my computer laboratory class. We were asked to replicate its functionality with no options passed as arguments or with just the -b, -n and -s options.



      I'm posting the code here because, although it works fine, i feel a little bit insecure about. Firstly because i think i "over-coded" it a bit, specially on the option handling part, and also, because i'm still not very confortable working with pointers and so i am not very sure if my approach does not generate memory leaks or malfunctions.



      Here it is:



      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      #include <unistd.h>
      #include <ctype.h>
      #define BUF_SIZE 1024

      int readStdin(int index, int bflag, int nflag)
      char buffer[BUF_SIZE];
      while(fgets(buffer, BUF_SIZE, stdin)) //reads from the standard input and prints the input
      if (nflag)
      printf(" %d %s", index, buffer);
      index++;

      if (bflag)
      if (*buffer == 'n')
      printf ("%s", buffer);

      else
      printf (" %d %s", index, buffer);
      index++;


      else
      printf("%s", buffer);


      return index; //returns the incremented index to perpetuate its use


      int readFile(char* filename, FILE* fp, int index, int bflag, int nflag)
      char ch;
      char s[BUF_SIZE];
      if (fp==NULL) //in case the file doesn't exist
      printf("%s: No such file or directoryn", filename);
      exit(1);


      if (bflag)
      while ((fgets(s,BUF_SIZE,fp)))
      if (strcmp(s,"n") == 0)
      printf (" %s", s);

      else
      printf (" %d %s", index, s);
      index++;


      fclose(fp);

      if (nflag)
      while ((fgets(s,BUF_SIZE,fp)))
      printf (" %d %s", index, s);
      index++;

      fclose(fp);

      else
      while ((ch=fgetc(fp)) != EOF) //printing loop
      putchar(ch);

      fclose(fp);

      return index;


      void readArgs(int argc, char* argv[])
      FILE* fp;
      int index = 1; //line index. to be used in case -b or -n is passed as an argument
      int option; //option passed as argument
      int bflag = 0; //-b option deactivated by default
      int nflag = 0; //-n option deactivated by default
      opterr = 0; //deactivates getopt's default error messages

      //checks if there are options passed as argument and updates their flags
      while ((option = getopt(argc, argv, "bn")) != -1)
      switch (option)
      case 'b':
      bflag = 1;
      break;
      case 'n':
      nflag = 1;
      break;
      case '?': //in case there was some problem
      exit(1);



      if (bflag == 1 && nflag == 1) //if -b and -n are passed as argument, b overrides n
      nflag = 0;


      for (int i=optind; i<argc; i++)
      if (*argv[i] == '-') //in case of '-' in argv[i], reads from stdin and prints
      index = readStdin(index, bflag, nflag);
      clearerr(stdin);

      else //prints the contents of the file in *argv[i]
      fp = fopen(argv[i], "r");
      index = readFile(argv[i], fp, index, bflag, nflag);




      int main(int argc, char* argv[])
      if (argc<2) //if there are no arguments
      readStdin(1,0,0);
      return 0;

      readArgs(argc, argv); //otherwise
      return 0;




      I didn't implement the -s option because i cant think of a way to handle it at the same time as the other options. That's why i think that the way i am handling the options part is a bit inefficient.



      Any suggestions?







      c





      share







      New contributor




      Guilherme Lima is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share







      New contributor




      Guilherme Lima is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share



      share






      New contributor




      Guilherme Lima is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 7 mins ago









      Guilherme LimaGuilherme Lima

      1




      1




      New contributor




      Guilherme Lima is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Guilherme Lima is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Guilherme Lima is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




















          0






          active

          oldest

          votes












          Your Answer





          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );






          Guilherme Lima is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217037%2flinux-cat-command-in-c%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          Guilherme Lima is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          Guilherme Lima is a new contributor. Be nice, and check out our Code of Conduct.












          Guilherme Lima is a new contributor. Be nice, and check out our Code of Conduct.











          Guilherme Lima is a new contributor. Be nice, and check out our Code of Conduct.














          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217037%2flinux-cat-command-in-c%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

          格濟夫卡 參考資料 导航菜单51°3′40″N 34°2′21″E / 51.06111°N 34.03917°E / 51.06111; 34.03917ГезівкаПогода в селі 编辑或修订