Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save outlinepix/65936032767abbbc465209e2361e75dd to your computer and use it in GitHub Desktop.
Save outlinepix/65936032767abbbc465209e2361e75dd to your computer and use it in GitHub Desktop.
Linux "wc" command implementation in C language.(Noobish)
/* compile using "gcc -o wc <file.c>" and work just like wc only tested on asci text file*/
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<unistd.h>
FILE * getFileBuffer(char * file_name);
int lineCount(char * filepath);
int wordCount(char * filepath);
int charCount(char * filepath);
void help();
int main(int argc, char *argv[])
{
if (argc == 1)
{
printf("No arguments provided\n");
help();
return 0;
}
printf(" ");
char *filepath = argv[(argc -1)];
int option;
while ((option = getopt(argc, argv, "wcl")) != -1) {
switch (option) {
case 'w':
printf("%d ", wordCount(filepath));
break;
case 'c':
printf("%d ", charCount(filepath));
break;
case 'l':
printf("%d ", lineCount(filepath));
break;
default:
printf("Invalid option\n");
help();
return 0;
}
}
printf("%s\n", filepath);
return 0;
}
/*functions*/
FILE * getFileBuffer(char * file_name){
FILE * file_buffer = fopen(file_name, "r");
if(file_buffer == NULL){
printf("File not found\n");
return NULL;
}
return file_buffer;
}
int lineCount(char * filepath){
FILE * file_buffer = getFileBuffer(filepath);
int count = 0;
char line[100];
while(fgets(line , sizeof(line), file_buffer))
{
count++;
}
return count;
}
int wordCount(char * filepath){
FILE * file_buffer = getFileBuffer(filepath);
int count = 0;
char line[100];
while(fgets(line , sizeof(line), file_buffer))
{
//count the number of words in the line
char * p = strtok(line, " ");
while(p != NULL)
{
count++;
p = strtok(NULL, " ");
}
}
return count;
}
int charCount(char * filepath){
FILE * file_buffer = getFileBuffer(filepath);
int count = 0;
char line[100];
while(fgets(line , sizeof(line), file_buffer))
{
count += strlen(line);
}
return count;
}
void help(){
FILE *file = fopen("../src/help.txt", "r");
char line[100];
while(fgets(line , sizeof(line), file))
{
printf("%s", line);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment