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;
}

You are reading a char when you first test for EOF to see if the file is empty and never put that char in your line or add it to the count. Just initialize count_char_line to 1 and set oneline[0] to c before you enter the do loop.

> char filename[] = "";
This has no space to store an input - instant buffer overflow and broken program.

Also, consider using fgets() to read each line, then deal with the line in memory.

commented: Yes. +8
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.