C String Input-Output using fscanf() and fprintf()
In C, you can perform string input and output operations using the fscanf()
and fprintf()
functions when working with files. These functions are particularly useful for reading and writing strings to and from files. Below, I'll provide examples of how to use these functions for string input and output.
String Input using fscanf()
:
#include <stdio.h>
int main() {
FILE *file;
char name[50];
// Open a file for reading
file = fopen("input.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// Read a string from the file using fscanf()
fscanf(file, "%s", name);
// Close the file
fclose(file);
// Print the read string
printf("Name: %s\n", name);
return 0;
}
In this example, we open a file named "input.txt" for reading, use fscanf()
to read a string, and then print the string.
String Output using fprintf()
:
#include <stdio.h>
int main() {
FILE *file;
char message[] = "This is a test message.";
// Open a file for writing
file = fopen("output.txt", "w");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// Write a string to the file using fprintf()
fprintf(file, "Message: %s\n", message);
// Close the file
fclose(file);
return 0;
}
In this example, we open a file named "output.txt" for writing, use fprintf()
to write a formatted string to the file, and then close the file.
Remember to include error handling to check if file operations succeed. You can adjust the file modes ("r" for reading and "w" for writing) and file paths as needed for your specific use case.
These examples demonstrate how to use fscanf()
and fprintf()
for string input and output when working with files in C.