how to add a number before every line in c language
To add a number before every line in C language, you can follow these steps:
- Declare a variable to store the line number, such as
int lineNumber = 1;
. - Open the file that contains the lines you want to number using the
fopen()
function. Make sure to check if the file was opened successfully. - Use a loop to read each line from the file until the end is reached. You can use the
fgets()
function to read a line at a time. - Inside the loop, print the line number followed by a tab or space character using the
printf()
function. For example,printf("%d\t", lineNumber);
orprintf("%d ", lineNumber);
. - Print the actual line content using the
printf()
function, or you can write it to another file if desired. - Increment the line number by 1 using the increment operator
++
. - Repeat steps 3-6 until all lines have been processed.
- Close the file using the
fclose()
function to free system resources.
Here is an example code snippet that demonstrates how to add line numbers before each line in C:
#include <stdio.h>
int main() {
FILE *file;
char line[100];
int lineNumber = 1;
file = fopen("input.txt", "r");
if (file == NULL) {
printf("Failed to open the file.\n");
return 1;
}
while (fgets(line, sizeof(line), file) != NULL) {
printf("%d\t%s", lineNumber, line);
lineNumber++;
}
fclose(file);
return 0;
}
In this example, we assume that there is a file named "input.txt" in the same directory as the C program. The program reads each line from the file using fgets()
and prints the line number followed by a tab character (\t
) and the line content using printf()
. The line number is incremented after each line is processed.
Make sure to adjust the file name and path according to your specific requirements.