Search code examples
cfiletextio

Trouble Opening File in C


I am very new to programming (and this website) so thank you for your help and your patience. I am writing a function that counts the number of lines in a text file, but opening the file always returns NULL. I am (mostly) sure that the file is in my current working directory, however I have the same issue when I use an absolute path. I have looked at lots of sample code but cannot for the life of me find where I'm going wrong.

This is the code I wrote to test opening the file:

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

int fileOpen(char *);

int main()
{
    printf("%d", fileOpen("My File.txt"));
    return 0;
}
int fileOpen(char *fileName) {
    FILE *fp = fopen(fileName,"r");

    if (fp == NULL);
    return -1;

    if (fp != NULL);
    return 1;
}

This always returns -1. Thank you again for any help you can give me, -Ian


Solution

  • Your issue is here

    if (fp == NULL);
            return -1;
    

    What you are essentially saying to the compiler is

    "If fp is null." As the ; acts to close that statement Instead you should only have a semicolon following the return -1; such that you are now saying

    "If fp is null, return -1."

    The semicolon acts to delimit full statements, not neccesarily just lines

        if (fp == NULL)
            return -1;