Prints new line after '\0' character in C -


i'm doing assignment recreate 3 switches of cat command, -n/-t/-e. compile , enter in 2 parameters, switch , file name. store textfile contents buffer.

int main(int argc, char *argv[]){  int index = 0; int number = 1; int fd, n, e, t; n = e = t = 0; char command[5];  char buffer[buffersize];  strcpy(command, argv[1]); fd = open(argv[2], o_rdonly); if( fd == -1) {     perror(argv[2]);     exit(1); }  read(fd, buffer,buffersize);  if( !strcmp("cat", command)){     printf("%s\n", buffer); } else if( !strcmp("-n", command)){     n = 1; } else if( !strcmp("-e", command)){     e = 1; } else if( !strcmp("-t", command)){     t = 1; } else if( !strcmp("-ne", command) || !strcmp("-en", command)){     n = e = 1; } else if( !strcmp("-nt", command) || !strcmp("-tn", command)){     n = t = 1; } else if( !strcmp("-et", command) || !strcmp("-te", command)){     t = e = 1; } else if( !strcmp("-net", command) || !strcmp("-nte", command) ||        !strcmp("-tne", command) || !strcmp("-ent", command) ||        !strcmp("-etn", command) || !strcmp("-ten", command)){     n = e = t = 1; } else{     printf("invalid switch entry"); }  if(n){     printf("%d  ", number++);  }  while(buffer[index++] != '\0' && ( n || e || t)){     if(buffer[index] == '\n' && e && n){         printf("$\n%d  ", number++);     }     else if(buffer[index] == '\n' && e){         printf("$\n");     }     else if(buffer[index] == '\t' && t){         printf("^i");     }     else if(buffer[index] == '\n' && n){         printf("\n%d  ", number++);     }     else {         printf("%c", buffer[index]);     } } printf("\n"); close(fd); return 0; 

}

everything works except when try use -n command. adds new line. use textfile has

hello   hello     hello world!  

instead of

1 hello  2  hello  3    hello world! 

it print out this:

1 hello  2  hello  3    hello world!  4 

for reason adds line after world!

am missing simple?

this might not fix problem, don't see code put terminating null character in buffer. try:

// reserve 1 character null terminator. ssize_t n = read(fd, buffer, buffersize-1); if ( n == -1  ) {    // deal error.    printf("unable read contents of file.\n");    exit(1); //??? }  buffer[n] = '\0'; 

Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -