I have the following code that simulate the wc command from linux. I need to use a buffer with the dimension of 4096 but for some reason when I execute this code i get the following result:
0 0 0 wcfile
I get 0 lines, words and bytes even if the file is not empty. The code that I am using is the following:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define LUNG_BUF 4096
int main(int argc, char** argv)
{
int bytes = 0;
int words = 0;
int newLine = 0;
char buffer[LUNG_BUF];
enum states { WHITESPACE, WORD };
int state = WHITESPACE;
if ( argc !=2 )
{
printf( "Nu ati introdu snumele fisierului\n%s", argv[0]);
}
else{
FILE *file = fopen( argv[1], "r");
if(file == 0){
printf("can not find :%s\n",argv[1]);
}
else{
char *thefile = argv[1];
while (read(fileno(file),buffer,LUNG_BUF) ==1 )
{
bytes++;
if ( buffer[0]== ' ' || buffer[0] == '\t' )
{
state = WHITESPACE;
}
else if (buffer[0]=='\n')
{
newLine++;
state = WHITESPACE;
}
else
{
if ( state == WHITESPACE )
{
words++;
}
state = WORD;
}
}
printf("%d %d %d %s\n",newLine,words,bytes,thefile);
}
}
}```