Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Write a bash script to print a particular line from a file in C
In C programming, we can read and print a specific line from a file using file handling functions. This involves opening the file, reading through it line by line, and printing the desired line number.
Syntax
FILE *fopen(const char *filename, const char *mode); char *fgets(char *str, int n, FILE *stream); int fclose(FILE *stream);
Method 1: Using Line Counter
This approach reads the file line by line and uses a counter to track the current line number −
Note: Create a text file named "text.txt" in the same directory with some content before running this program.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file;
char line[256];
int lineNumber = 5; /* Line number to print */
int currentLine = 1;
/* Open file for reading */
file = fopen("text.txt", "r");
if (file == NULL) {
printf("Error: Could not open file text.txt<br>");
return 1;
}
/* Read file line by line */
while (fgets(line, sizeof(line), file) != NULL) {
if (currentLine == lineNumber) {
printf("Line %d: %s", lineNumber, line);
break;
}
currentLine++;
}
if (currentLine < lineNumber) {
printf("File has only %d lines<br>", currentLine - 1);
}
fclose(file);
return 0;
}
Method 2: Using Dynamic Line Number Input
This approach allows the user to specify which line number to print −
#include <stdio.h>
#include <stdlib.h>
void printSpecificLine(const char *filename, int targetLine) {
FILE *file;
char buffer[1024];
int currentLine = 1;
int found = 0;
file = fopen(filename, "r");
if (file == NULL) {
printf("Error: Cannot open file %s<br>", filename);
return;
}
while (fgets(buffer, sizeof(buffer), file) != NULL) {
if (currentLine == targetLine) {
printf("Line %d: %s", targetLine, buffer);
found = 1;
break;
}
currentLine++;
}
if (!found) {
printf("Line %d not found. File has %d lines.<br>", targetLine, currentLine - 1);
}
fclose(file);
}
int main() {
char filename[] = "text.txt";
int lineNumber = 3;
printf("Reading line %d from file %s:<br>", lineNumber, filename);
printSpecificLine(filename, lineNumber);
return 0;
}
Key Points
- Always check if
fopen()returnsNULLto handle file opening errors. - Use
fgets()to read lines safely with buffer size limits. - Remember to close the file using
fclose()after reading. - Line numbering typically starts from 1, not 0.
Conclusion
Reading specific lines from files in C requires careful file handling and line counting. The methods shown provide robust solutions for extracting particular lines while handling edge cases like missing files or insufficient line counts.
