Search_string in a loop of different files in C - c

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!

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;
}

Related

fopen won't open file, providing the full path via fgets

I need to open a file, providing the full path. I used the function fopen to open the file, this works
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE *file;
file = fopen("C:\\Users\\Edo\\Desktop\\sample.docx","rb");
if (file == NULL) {
printf("Error");
exit(0);
}
return 0;
}
but what i really need is to let the user choose which file he wants, however this code does not work .
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE *file;
char path[300];
printf("Insert string: ");
fgets(path, 300, stdin);
file = fopen(path,"rb");
if (file == NULL) {
printf("Error");
exit(0);
}
return 0;
}
I tried as input:
C:\Users\Edo\Desktop\sample.docx
C:\\Users\\Edo\\Desktop\\sample.docx
C:/Users/Edo/Desktop/sample.docx
C://Users//Edo//Desktop//sample.docx
none of them works
fgets leaves the newline on the end of your string. You'll need to strip that off:
path[strlen (path) - 1] = '\0';
You'll need to #include <string.h> for this too.
Thanks #lurker, he told me what was the problem, I fixed the code this way
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
FILE *file;
char path[300];
printf("Insert string: ");
fgets(path, 300, stdin);
strtok(path, "\n");
file = fopen(path,"rb");
if (file == NULL) {
printf("Error");
exit(0);
}
return 0;
}

Directory listing with wildcards in C

Is there a ready-made function in C that can list the contents of a directory using wildcards to filter out file names, for example, the equivalent of:
echo [!b]????
which shows the names of directory entries that are four characters long and do not start with "b"?
I know I can use scandir, but then, I need to provide my own filter function:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int filter(const struct dirent *entry)
{
if (strlen(entry->d_name) == 4 && entry->d_name[0] != 'b') return 1;
else return 0;
}
void main(void)
{
struct dirent **list;
int count;
count=scandir(".", &list, filter, alphasort)-1;
if (count < 0)
puts("Cannot open directory");
else
for (; count >= 0; count--)
puts(list[count]->d_name);
free(list);
}
Honestly, I am seriously considering actually calling shell to do it for me:
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
FILE *fp;
char buffer[1024];
fp=popen("echo [!b]???", "r");
if (fp == NULL)
puts("Failed to run command.");
else
while (fgets(buffer, sizeof(buffer), fp) != NULL)
puts(buffer);
pclose(fp);
}
As mentioned in the comments the glob() function would be pretty good for this:
#include <stdio.h>
#include <glob.h>
int
main (void)
{
int i=0;
glob_t globbuf;
if (!glob("[!b]????", 0, NULL, &globbuf)) {
for (i=0; i <globbuf.gl_pathc; i++) {
printf("%s ",globbuf.gl_pathv[i]);
}
printf("\n");
globfree(&globbuf);
} else
printf("Error: glob()\n");
}

File pointers led to core dump. Probably something stupid

Write the program myuniq.c that contains a function void process_file(FILE* f) that reads all input from the given file one line at the time while keeping two consecutive lines in memory, and prints each line to the standard output if it is not equal to the previously read line.
^^This is the assignment i'm working on. My code below is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process_file(FILE* f);
int main()
{
FILE *fil = fopen("text.txt","r");
process_file(fil);
return 0;
}
void process_file(FILE* f)
{
FILE *fi = f;
char *firstLine = fgets(firstLine, 999, f);
char *secondLine = fgets(secondLine, 999, f);
while (feof(fi))
{
if (firstLine == secondLine)
{
puts(secondLine);
}
else
{
puts(firstLine);
puts(secondLine);
}
firstLine++;
secondLine++;
}
}
It compiled fine...but on every run it says core dumped. I can't see where I went wrong? Any ideas?
You don't check the return value of fopen, you don't allocate any memory for the strings into which you read, you don't continue reading input from the file, you don't correctly check for the end of input.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MY_MAX_LINE 999
void process_file(FILE* f)
{
char firstLine[MY_MAX_LINE + 1];
char secondLine[MY_MAX_LINE + 1];
while (1)
{
if (!fgets(firstLine, sizeof(firstLine), f))
break;
puts(firstLine);
if (!fgets(secondLine, sizeof(secondLine), f))
break;
if (strncmp(firstLine, secondLine, sizeof(firstLine)))
puts(secondLine);
}
if (!feof(f))
perror("Problem reading from file"), exit(1);
}
int main(int argc, char **argv)
{
FILE *f = fopen("text.txt", "r");
if (!f)
perror("text.txt"), exit(1);
process_file(f);
fclose(f);
return 0;
}

Reading Text In C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
int main(){
int JourneyId;
char Date[MAX];
int Hour;
char BusDriver[MAX];
char Departure[MAX];
char Destination[MAX];
int BusCapacity;
FILE * file;
file = fopen( "Journey.txt" , "rt");
if(file){
while (fscanf(file,"%d,%s,%d,%20[^,],%20[^,],%20[^,],%d", &JourneyId,Date,&Hour,BusDriver,Departure,Destination, &BusCapacity) != EOF){
printf("%d,",JourneyId);
printf("%s",BusDriver);
}
}
else{
printf("Error");
}
return 1;
}
I want to read text file and use this code for adding BST.But If I run , Output is infinite loop.How can I read text file ?
Text file which I want to read:
80,15.04.2014,10,Henry Ford,NewYork,Paris,45
40,15.04.2014,11,Nikola Tesla,Londra,NewYork,40
Rather than read a text file using fscanf(), strongly recommend using fgets() and then parsing via sscanf(), strtok(), strtol(), etc. Check all function return values. It is much easier to cope with the unexpected - which is certainly what is happening in OP's case.
Using modified format from #BLUEPIXY
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
int main() {
int JourneyId;
char Date[MAX];
int Hour;
char BusDriver[MAX];
char Departure[MAX];
char Destination[MAX];
int BusCapacity;
FILE * file;
file = fopen("Journey.txt", "rt");
if (file) {
char buf[MAX*4 + 20*3 + 6*1 + 3];
while (fgets(buf, sizeof buf, stdin) != NULL) {
int cnt = sscanf(buf, "%d,%499[^,],%d,%499[^,],%499[^,],%499[^,],%d",
&JourneyId, Date, &Hour, BusDriver, Departure, Destination,
&BusCapacity);
if (cnt != 7) {
printf("Unexpected input \"%s\"", buf);
break;
}
printf("%d,", JourneyId);
printf("%s\n", BusDriver);
}
fclose(file); // Be sure to close
} else {
printf("Error opening\n");
}
return 1;
}
As #BLUPIXY indicated, The following functions (tried on SuSE Linux / gcc)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
int main(){
int JourneyId;
char Date[MAX];
int Hour;
char BusDriver[MAX];
char Departure[MAX];
char Destination[MAX];
int BusCapacity;
FILE *file;
file = fopen( "Journey.txt" , "rt");
if(file)
{
// while(fscanf(file,"%d,%s,%d,%20[^,],%20[^,],%20[^,],%d", &JourneyId,Date,&Hour,BusDriver,Departure,Destination, &BusCapacity) != EOF){
while(fscanf(file,"%d,%11[^,],%d,%20[^,],%20[^,],%20[^,],%d", &JourneyId,Date,&Hour,BusDriver,Departure,Destination, &BusCapacity) != EOF){
printf("%d,",JourneyId);
printf("%s",BusDriver);
}
}
else
{
printf("Error");
}
return 1;
}

Read WORDS (not char) from file without empty lines in C - not duplicated [duplicate]

This question already has an answer here:
Read text from file skipping any spaces or empty lines
(1 answer)
Closed 8 years ago.
Hi.
I need to read several files without empty lines between words.They can have different layouts, such as 1.txt or 2.txt:
1.txt:
treg
hreger
ig
srg
fre
ig
lre
eg
2.txt:
lregreg
igregr
kreggerg
ereherh
tershs
hsehsteh
asreh
treshse
How do i do that ? How can I count the number of words in the fastest way?
I just have the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
FILE *fp;
char palavra[50]="/0";
char *s;
fp = fopen("1.txt","r");
if(fp == NULL){
puts("Open file failed\n");
exit(-1);
}
while(fscanf(fp,"%s",palavra)!=EOF){
s=palavra;
/*do things with s var*/
}
fclose(fp);
exit(0);
}
how i implement something like that:
while ((c = fgetc(fp)) != EOF) {
if (isspace(c)){
continue;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
enum status { OUT, IN };
int main(){
FILE *fp;
int ch, wc = 0, stat = OUT;
if(NULL==(fp = fopen("1.txt","r"))){
fprintf(stderr, "Open file failed\n");
exit(-1);
}
while(EOF!=(ch=fgetc(fp))){
if(isspace(ch)){
stat = OUT;
} else {
if(stat == OUT){
stat = IN;
++wc;
}
}
}
fclose(fp);
printf("number of words is %d.\n", wc);
return 0;
}

Resources