Issue
I don't know how to solve this problem. I have this function that prints all the .txt files that I have, but I also need to search and print, after each file name, some specific strings (of each file) that contain some word. This is the part that prints the name of the files.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <dirent.h>
int main() {
DIR* p;
struct dirent* pp;
p = opendir("./");
if (p != NULL) {
while ((pp = readdir(p)) != NULL) {
int length = strlen(pp->d_name);
if (strncmp(pp->d_name + length - 4, ".txt", 4) == 0)
puts(pp->d_name);
}
(void)closedir(p);
}
return 0;
}
I need to search some specific words (three different words) and print the line in where are contained, that would be three different lines.
Right now the program prints this:
0_email.txt
1_email.txt
Inside this files that are like emails, I need to print he date of when they were send (Date:), who (To:) and the subject (Subject:). This information is not always in the same line. I have try this code, that search the word, but I am not able to make the program search in all the files (because this files can increase and have different names, no I can't not do it name by name) and to search several times
FILE *fp;
char filename[]="0_email.txt",line[200],search_string[]="To:";
fp=fopen(filename,"r");
if(!fp){
perror("could not find the file");
exit(0);
}
while ( fgets ( line, 200, fp ) != NULL ){
if(strstr(line,search_string))
fputs ( line, stdout );
}
fclose ( fp );
This second code is one that I found in Internet, I have just learn c programming and I'm not very familiar with it.
Thanks for your help!
Solution
You need to learn about functions.
You roughly need following:
It's untested code and there is still a lot of improvments that should be done. It does not exactly what you want and I'm not even sure if it compiles, but it should give you an idea what you need to do:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <dirent.h>
int CheckFile(const char *filename)
{
FILE *fp;
char line[200], search_string[] = "To:";
fp = fopen(filename, "r");
if (!fp) {
perror("could not find the file");
exit(0);
}
while (fgets(line, 200, fp) != NULL) {
if (strstr(line, search_string))
fputs(line, stdout);
}
fclose(fp);
}
int main() {
DIR* p;
struct dirent* pp;
p = opendir("./");
if (p != NULL) {
while ((pp = readdir(p)) != NULL) {
int length = strlen(pp->d_name);
if (strncmp(pp->d_name + length - 4, ".txt", 4) == 0)
CheckFile(pp->d_name);
}
(void)closedir(p);
}
return 0;
}
Answered By - Jabberwocky
Answer Checked By - Willingham (JavaFixing Volunteer)