0

I have implemented a very simple function from thenewboston's (C Programming Tutorial - 51 - How to Read Files), but I keep getting a segmentation fault when I run the executable file. This same function will work fine when I just have it on one main.c file. However, once I have 2 .c files and 1 .h file and make an executable, the problem occurs.

gcc command

gcc -o main main.c test.c

main.c

#include <stdio.h>
#include "test.h"


int main()
{
    int size = 0;
    letsRead("bacon.txt", &size);
    
    return 0;
}

test.h

#ifndef __TEST_H__
#define __TEST_H__
    
void letsRead (char *filename, int *size);

#endif

test.c

#include <stdio.h>
#include <stdlib.h>

void letsRead (char *filename, int *size)
{
    FILE * fPointer;
    fPointer = fopen(filename, "r");
    char singleLine[150];

    while(!feof(fPointer))
    {
        fgets(singleLine, 150, fPointer);
        puts(singleLine);
    }
    //int count = 0;

    fclose(fPointer);
}

bacon.txt

this is bacon
this is not bacon
this is bacon sandwich
Bob
  • 21
  • 3
  • 1
    This likely has nothing to do with zsh. What have you learned with your debugger? – Stephen Newell Sep 05 '22 at 19:11
  • [Why is “while( !feof(file) )” always wrong?](https://stackoverflow.com/q/5431941/6699433) – klutt Sep 05 '22 at 19:14
  • The code read and prints out the txt file fine when I have "letsRead" function on top of the main function of main.c. It is only when I have multiple .c files I get this segmentation fault error. – Bob Sep 05 '22 at 19:17
  • Read the question I linked. Your logic is wrong. – klutt Sep 05 '22 at 19:22
  • Does this mean I have to change !feof(file)? How should I replace this line? Also, why would this work fine when I run the code without creating an executable? – Bob Sep 05 '22 at 21:12

0 Answers0