c language append line to file
To append a line to a file in C, you can follow these steps:
- Open the file in append mode using the
fopen()
function with the"a"
mode specifier. - Check if the file was opened successfully by comparing the file pointer returned by
fopen()
toNULL
. - Use the
fprintf()
function to write the line to the file. Pass the file pointer, followed by the line you want to append, as arguments tofprintf()
. - Close the file using the
fclose()
function to release the resources associated with it.
Here is an example code snippet that demonstrates appending a line to a file in C:
#include <stdio.h>
int main() {
FILE *file;
char line[100];
// Open the file in append mode
file = fopen("filename.txt", "a");
// Check if the file was opened successfully
if (file == NULL) {
printf("Unable to open the file.\n");
return 1;
}
// Get the line from the user
printf("Enter the line to append: ");
fgets(line, sizeof(line), stdin);
// Append the line to the file
fprintf(file, "%s", line);
// Close the file
fclose(file);
return 0;
}
In this example, the program prompts the user to enter a line, and then it appends that line to the file named "filename.txt". You can replace "filename.txt" with the actual path and name of the file you want to append to.