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
How to make payment on the internet without leaving a money trail?
Can I make popcorn with any corn?
Disadvantages of online checking accounts?
What are these boxed doors outside store fronts in New York?
"which" command doesn't work / path of Safari?
What defenses are there against being summoned by the Gate spell?
How to report a triplet of septets in NMR tabulation?
If Manufacturer spice model and Datasheet give different values which should I use?
The use of multiple foreign keys on same column in SQL Server
Accidentally leaked the solution to an assignment, what to do now? (I'm the prof)
Find original functions from a composite function
Infinite past with a beginning?
How can I fix this gap between bookcases I made?
Should I join office cleaning event for free?
Compute hash value according to multiplication method
What is the command to reset a PC without deleting any files
The magic money tree problem
Is the month field really deprecated?
Option clash between elsarticle and titlesec?
Pronouncing Dictionary.com's W.O.D "vade mecum" in English
Theorems that impeded progress
A newer friend of my brother's gave him a load of baseball cards that are supposedly extremely valuable. Is this a scam?
TGV timetables / schedules?
How is this relation reflexive?
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;
$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?
c
New contributor
$endgroup$
add a comment |
$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?
c
New contributor
$endgroup$
add a comment |
$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?
c
New contributor
$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
c
New contributor
New contributor
New contributor
asked 14 mins ago
Guilherme LimaGuilherme Lima
1
1
New contributor
New contributor
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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.
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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