Problems with readdir() and fgets

627 views Asked by At

I'm writing a code where I can be given a directory of .txt files, and specific strings that appear throughout each file, and do some simple comparisons. code chunk will be posted below.

So, My task:Open directory>open file>compare strings>open next file(repeat) Until I run out of files.

What is wrong:My code currently prints the first file name( full path name) infinitely until it crashes, nothing is printed to fp1. It is supposed to only print the file name once, but it never gets past that first file, where, obviously, I would like it to go through all the files in the directory.

I'm sorry that I'm fairly new to C so I might be unclear as to how these functions actually operate.

Please correct me if I'm wrong, I want to see if I understand correctly.

while ((in_file = readdir(FD))!= NULL){

Should basically traverse through a directory and "look" the name of each file. I then do some very inefficient work around, which you will probably laugh at me for, and I manage to get the full path name of the first file in the directory. I then assign that path name to entry_file pointer, where it gets opened by fgets(). I believe fgets() should read each line individually until it sees a EOF character

Now, I had this section working before I added the directory stuff, where I was just opening one file by using fopen() with its full path name, and I haven't touched it. So I don't think my problem is here, but nothing is being printed to fp1 at all, so I really don't know.

I then do some simple string comparisons and try to print matches to fp1 When it reaches the end of the file, it should close the file, and then go back up to readdir() and repeat the process with the next file

Thank you so much for any help. I probably sound like an idiot, but I just have no idea what could cause this.

Yes, I realize its very messy, and I have many unused and pointless variables. I've been trying to figure this out for days, trying many different methods.

int main(void)
{

char str1[10000];
char str2[] = { "Measure L1 current Tank Heater ON: Passed" };
char str3[] = { "Measure L1 current Tank Heater ON: Failed" };
char str4[] = { "Measure L1 current Manifold Heater ON: Passed" };
char str5[] = { "Measure L1 current Manifold Heater ON: Failed" };
char str6[] = { "Measure L1 current (verify heaters off) Manifold: Passed" };
char str7[] = { "Measure L1 current (verify heaters off) Manifold: Failed" };
char sn[] = { "Serial Number:                1" };
DIR* FD;
struct dirent* in_file;
int lcount = 0;//line counter
char *ret;
int linenum = 0;//temp line count
char mes[500];//measurement
double val = 0;//value
char unit[500];//units
char pathstr1[38] = ("C:/Users/liam.king/Desktop/TestFiles/");
char pathstr2[200];


DWORD retval = 0;

char buffer[BUFSIZE] = ("");
char buf[BUFSIZE] = ("");
char** lppPart = {NULL};

FILE *fp, *fp1, *filewrite;
FILE *entry_file;
//fp = fopen("C:/Users/liam.king/Desktop/TestFiles/ProBlueUnit_UpgradeRev4_Report[1022230.SA15E14082][9 39 00 AM][5 19 2015].txt", "r");
fp1 = fopen("C:/Users/liam.king/Desktop/ProBlueTestWrite.txt", "a");
filewrite = fopen("C:/Users/liam.king/Desktop/FileWrite.txt", "w+");
if (fp1 == NULL){
    printf("Invalid file name");
    return 0;
}

if ((FD = opendir(LONG_DIR_NAME))==NULL)
{
    printf("Error: Failed to open directory\n");


    return 0;
}
else{
    printf("Directory opened successful\n");
}
while ((in_file = readdir(FD))!= NULL){

    if (strcmp(in_file->d_name, ".") == 0 || strcmp(in_file->d_name, "..") == 0)
        continue;


    fprintf(filewrite, "%s", pathstr1);
    fprintf(filewrite,"%s", in_file->d_name);
    fclose(filewrite);

    filewrite = fopen("C:/Users/liam.king/Desktop/FileWrite.txt", "r");



        fscanf(filewrite, "%[^\n]%*c", pathstr2);
        printf("%s\n", pathstr2);//check file name is correct

        entry_file = fopen(pathstr2, "r");
        fclose(filewrite);


        if (entry_file != NULL){
            //printf("SUCCESSFULL OPENING\n");
            //fprintf(fp1, "Does this work?\n");


        }
        else if (entry_file == NULL){
            printf("Error: Failed to open entry file\n");
            return 0;

        }

            while (fgets(buffer, 256, entry_file) != NULL){//string being stored in str1 from file *entry_file

lcount++;
                ret = strstr(str1, sn);
                if (ret != NULL){
                    fprintf(fp1, "%s\n", str1);
                }
                ret = strstr(str1, str2);
                if (ret != NULL){// compares str1 and 2
                    fprintf(fp1, "Found"" %s ""at line %d\n", str1, lcount);//if same, declare match and what line found at. 
                    linenum = lcount;
                }
//comparing more strings

            }
            fclose(entry_file);

    }

fclose(fp1);

return 0;
}
1

There are 1 answers

2
chqrlie On

Since pathstr2 is declared as a local array, you should use this:

while ((in_file = readdir(FD)) != NULL) {
    if (!strcmp(in_file->d_name, ".") || !strcmp(in_file->d_name, ".."))
        continue;

    snprintf(pathstr2, sizeof(pathstr2), "%s%s", pathstr1, in_file->d_name);
    entry_file = fopen(pathstr2, "r");
    ...
    while (fgets(buffer, sizeof(buffer), entry_file) != NULL) {
        lcount++;
        if (strstr(buffer, sn)) {
            fprintf(fp1, "%s", buffer);
        }
        if (strstr(buffer, str1)) {
            fprintf(fp1, "Found \"%s\" at line %d\n", str1, lcount);
            linenum = lcount;
        }
        ...
    }
    fclose(entry_file);
}

The tests you perform with strstr on the lines read from entry_file are not incorrect. You should specify buffer instead of str1 as the first argument.

Also note that strstr searches for the second string in the whole line. If the string should be starting at the beginning of the line, you should write:

if (!strncmp(buffer, str1, strlen(str1))) {
    // line starts with str1
}