user2923535
user2923535

Reputation: 594

Having trouble using fprintf in a recursive function

I'm using a recursive function that given a directory, scans through it and prints out all the files and child directories. It also prints the file list to a txt file.

My stdout is:

    [test]
      [empty]
        [notreally]
          [real empty]
        - haha.txt
      - readme.txt
    - test2.c
    - test.c

Where the folders are in the []. This is what I expect the stdout to be but when I check my log.txt it isn't the same:

          [real empty]
        [notreally]
        - haha.txt
      [empty]
      - readme.txt
    [test]
    - test2.c
    - test.c

If I change the FILE *log = fopen(logFilePath,"a+"); to FILE *log = fopen(logFilePath,"w"); then the output to log.txt would be:

[test]
- test2.c
- test.c
.txt

Upvotes: 0

Views: 237

Answers (1)

piokuc
piokuc

Reputation: 26174

You forgot about the parens. This:

else
    printf("%*s- %s\n", level*2, "", entry->d_name);
    fprintf(log,"%*s- %s\n", level*2, "", entry->d_name);

should be

else {
    printf("%*s- %s\n", level*2, "", entry->d_name);
    fprintf(log,"%*s- %s\n", level*2, "", entry->d_name);
}

Also, don't open and close the file every time you see a file. Open it once for writing ("w")and pass it to the function. Don't open the file for appending in the function, take the fopen out of the function.

Upvotes: 1

Related Questions