how to search in a file in c
To search in a file in C, you can use the fopen
, fscanf
, and fclose
functions. Here's an example code snippet:
#include <stdio.h>
int main() {
FILE *file;
char search[100];
char word[100];
// Open the file in read mode
file = fopen("filename.txt", "r");
// Check if the file was opened successfully
if (file == NULL) {
printf("File not found.\n");
return 1;
}
// Get the word to search
printf("Enter a word to search: ");
scanf("%s", search);
// Search for the word in the file
while (fscanf(file, "%s", word) != EOF) {
if (strcmp(word, search) == 0) {
printf("Word found.\n");
break;
}
}
// Close the file
fclose(file);
return 0;
}
In this code, replace "filename.txt"
with the name of the file you want to search in. The program prompts the user to enter a word to search, and it scans each word in the file until a match is found or the end of the file is reached.
Please note that this is a basic example and assumes that the file contains only words separated by spaces. You can modify the code to suit your specific requirements.
[[SOURCE 1]]