I write a C program that reads a text file and copies it to standard output, adding to the start of each line the line number and the number of characters in the line. For example, if file contained the following:
Hello Daniweb forum
How are you today?
Good day
The output would be:
1 19 Hello.... forum
2 18 How.....today?
3 8 Good day
Here is my code. Unfortunately, it always miss one beginning character of the first line :( Can you help me dear members? you may use my attach text file for testing.
#include <stdio.h>
#include <stdlib.h>
int main(void){
char filename[] = "";
FILE *fp;
char oneline[255];
int c, count_char_line, total_char, linenum;
puts("Enter a file name: ");
scanf("%s",filename);
if((fp = fopen(filename, "r")) == NULL){
perror("Error opening such file");
exit(1);
}else if((c = fgetc(fp)) == EOF){
fputs("This file does not have data",stderr);
}else{
count_char_line = 0;
linenum = 0;
do{
c = fgetc(fp);
if(c != '\n'){
oneline[count_char_line] = c;
count_char_line++;
}else{
linenum++;
oneline[count_char_line] = '\0';
printf("%d %d %s\n\n",linenum, count_char_line, oneline);
count_char_line = 0;
}
}while(c != EOF);
fclose(fp);
}
return EXIT_SUCCESS;
}