How do I delete a specific line from text file in C?
Categories:
How to Delete a Specific Line from a Text File in C

Learn various robust methods to remove a particular line from a text file using C programming, covering temporary files, in-memory processing, and error handling.
Deleting a specific line from a text file in C is a common task that requires careful file manipulation. Unlike in-memory data structures, files do not allow direct deletion of a line by simply shifting subsequent content. Instead, you typically need to read the file, identify the line to be deleted, and then write the remaining content to a new location. This article explores several effective strategies to achieve this, focusing on robustness and efficiency.
Understanding the Challenge
When you want to remove a line from a text file, you're essentially performing a rewrite operation. The operating system's file I/O functions don't provide a direct 'delete line' primitive. This means you cannot simply 'punch a hole' in the middle of a file and expect the rest of the content to shift up. The common approach involves reading the original file line by line, deciding which lines to keep, and writing those lines to a new, temporary file. Once the process is complete, the original file is replaced with the temporary one.
flowchart TD A[Start] --> B{Open Original File} B --> C{Open Temporary File} C --> D{Read Line from Original File} D --> E{Is this the line to delete?} E -- No --> F[Write Line to Temporary File] E -- Yes --> G[Skip Line] F --> D G --> D D -- End of File --> H{Close Both Files} H --> I{Delete Original File} I --> J{Rename Temporary File to Original} J --> K[End]
Process Flow for Deleting a Line Using a Temporary File
Method 1: Using a Temporary File (Recommended)
This is the most common and robust method. It involves creating a new temporary file, copying all lines from the original file except the one you want to delete, and then replacing the original file with the temporary one. This approach is safe because if an error occurs during the copy process, your original file remains intact.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 256
void delete_line(const char *filename, int line_to_delete) {
FILE *original_file, *temp_file;
char buffer[MAX_LINE_LENGTH];
int current_line = 0;
original_file = fopen(filename, "r");
if (original_file == NULL) {
perror("Error opening original file");
return;
}
temp_file = fopen("temp.txt", "w");
if (temp_file == NULL) {
perror("Error creating temporary file");
fclose(original_file);
return;
}
while (fgets(buffer, MAX_LINE_LENGTH, original_file) != NULL) {
current_line++;
// If the current line is not the one to delete, write it to the temp file
if (current_line != line_to_delete) {
fputs(buffer, temp_file);
}
}
fclose(original_file);
fclose(temp_file);
// Delete the original file
if (remove(filename) != 0) {
perror("Error deleting original file");
return;
}
// Rename the temporary file to the original filename
if (rename("temp.txt", filename) != 0) {
perror("Error renaming temporary file");
return;
}
printf("Line %d deleted successfully from %s.\n", line_to_delete, filename);
}
int main() {
// Create a dummy file for testing
FILE *fp = fopen("example.txt", "w");
if (fp == NULL) {
perror("Error creating example.txt");
return 1;
}
fprintf(fp, "Line 1: Apple\n");
fprintf(fp, "Line 2: Banana\n");
fprintf(fp, "Line 3: Cherry\n");
fprintf(fp, "Line 4: Date\n");
fclose(fp);
printf("Original file content:\n");
fp = fopen("example.txt", "r");
char c;
while ((c = fgetc(fp)) != EOF) {
putchar(c);
}
fclose(fp);
printf("--------------------\n");
// Delete line 3
delete_line("example.txt", 3);
printf("\nFile content after deletion:\n");
fp = fopen("example.txt", "r");
if (fp == NULL) {
perror("Error opening example.txt after deletion");
return 1;
}
while ((c = fgetc(fp)) != EOF) {
putchar(c);
}
fclose(fp);
return 0;
}
C code to delete a line using a temporary file.
fopen
, remove
, and rename
to ensure operations succeed. This prevents data loss or corruption.Method 2: In-Memory Processing (for smaller files)
For very small files, you might consider reading the entire file content into memory, processing it (removing the desired line), and then writing the modified content back to the original file. This avoids the temporary file creation and renaming steps but is not suitable for large files due to memory constraints.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_FILE_SIZE 1024 * 10 // 10KB max file size for this example
void delete_line_in_memory(const char *filename, int line_to_delete) {
FILE *fp;
char *file_content = (char *)malloc(MAX_FILE_SIZE);
if (file_content == NULL) {
perror("Memory allocation failed");
return;
}
file_content[0] = '\0'; // Initialize to empty string
fp = fopen(filename, "r");
if (fp == NULL) {
perror("Error opening file for reading");
free(file_content);
return;
}
char buffer[MAX_LINE_LENGTH];
int current_line = 0;
long current_content_length = 0;
while (fgets(buffer, MAX_LINE_LENGTH, fp) != NULL) {
current_line++;
if (current_line != line_to_delete) {
// Check if adding this line would exceed MAX_FILE_SIZE
if (current_content_length + strlen(buffer) >= MAX_FILE_SIZE) {
fprintf(stderr, "File content exceeds buffer size. Aborting in-memory deletion.\n");
fclose(fp);
free(file_content);
return;
}
strcat(file_content, buffer);
current_content_length += strlen(buffer);
}
}
fclose(fp);
fp = fopen(filename, "w"); // Open in write mode to truncate and overwrite
if (fp == NULL) {
perror("Error opening file for writing");
free(file_content);
return;
}
fputs(file_content, fp);
fclose(fp);
free(file_content);
printf("Line %d deleted successfully from %s (in-memory method).\n", line_to_delete, filename);
}
int main() {
// Create a dummy file for testing
FILE *fp = fopen("example_in_memory.txt", "w");
if (fp == NULL) {
perror("Error creating example_in_memory.txt");
return 1;
}
fprintf(fp, "Line A: Alpha\n");
fprintf(fp, "Line B: Beta\n");
fprintf(fp, "Line C: Gamma\n");
fprintf(fp, "Line D: Delta\n");
fclose(fp);
printf("Original file content (in-memory test):\n");
fp = fopen("example_in_memory.txt", "r");
char c;
while ((c = fgetc(fp)) != EOF) {
putchar(c);
}
fclose(fp);
printf("--------------------\n");
// Delete line 2
delete_line_in_memory("example_in_memory.txt", 2);
printf("\nFile content after deletion (in-memory test):\n");
fp = fopen("example_in_memory.txt", "r");
if (fp == NULL) {
perror("Error opening example_in_memory.txt after deletion");
return 1;
}
while ((c = fgetc(fp)) != EOF) {
putchar(c);
}
fclose(fp);
return 0;
}
C code to delete a line by loading the file into memory.
Choosing the Right Method
For most applications, especially when dealing with files of unknown or potentially large sizes, the temporary file method is the safest and most reliable. It offers better error recovery and doesn't strain system memory. The in-memory method is only viable for very small, controlled files where performance might be marginally better due to fewer disk operations, but the risks often outweigh the benefits.
1. Prepare Your Environment
Ensure you have a C compiler (like GCC) installed on your system. Create a sample text file to test the deletion functions.
2. Implement the Temporary File Method
Copy the code for delete_line
into a .c
file. Compile it using gcc your_program.c -o your_program
and run it. Observe how the original file is modified.
3. Test with Edge Cases
Try deleting the first line, the last line, or a line number that doesn't exist. Ensure your error handling (e.g., for file opening) is robust.
4. Consider In-Memory for Small Files
If your application strictly deals with tiny files (e.g., configuration files under a few KB), you can experiment with the delete_line_in_memory
function, but be mindful of its limitations.