0

Hi guys i have a problem when I try to open a file. In a function when i try to read an existing text file, after i initialized the file pointer i still get the error "cannot open the file", this is the code:

FILE * fp;
fp = NULL;
fp=fopen("results.txt","r");
if(fp==NULL){

    printf("error!");
    exit(1);
}

using the debugger i can see the fp initialized to NULL, as requested. In the next order i can see its value changed to '0x751d9c68'. So now it's not NULL, but the program still prints error.

PS: I used the same code to open another file in another program (that works): as always the initial value of fp is NULL, then it's changed to '0x751d9c68' (yes, it has the same value in both programs), but this time works, because fp is in fact different from NULL.

PPS: I'm using Codelite, if that helps.

EDIT: adding a printf("%p\n", fp); prints this "751D9C68"

    Atleta * leggiRisultati (char fileName [], int * dim){FILE * fp; int count, i;

    Atleta temp;
     fp = NULL;
    fp=fopen(fileName,"r");
    printf("%p\n", fp);
    if(fp==NULL){

   perror("Error");

}


while (fscanf (fp, "%s%s%d%d%d", temp.cod, temp.nome, &temp.tN, &temp.tB, &temp.tC)== 5)
count ++;
rewind (fp);

 Atleta * atl = (Atleta*) malloc(count * sizeof(Atleta));


 for (i=0; i<count; i++){
  int nr = fscanf(fp, "%s%s%d%d%d",atl[i].cod, atl[i].nome, &atl[i].tN, &atl[i].tB, &atl[i].tC);
  //just controlling if the reading is done properly
    if (nr < 4) {
        printf ("cannot read the file %s",fileName);
        exit (1);
    }

   } fclose(fp);
    return atl;
 }

I then use this function in this main

  int main (){ int dim; Atleta * a; int i;

a = leggiRisultati("risultati.txt", &dim);

for (i =0; i<dim;i++){
stampaRisultato(a[i]);}

return 0;

}

Where "stampaRisultato" prints a line of the file just read and "Atleta" is a struct defined as:

 typedef struct {
char cod[5];
char nome[21];
int tN, tB, tC;
  }Atleta;

And last, yes the text file is in the same directory as my executable, yes I have the permission to open the file, the file contains a certain number of lines with 2 strings and 3 int each.

Rick
  • 21
  • 1
  • 6
  • 3
    Given that your code prints `error!` and not `cannot open the file`, I would assume you're not showing us everything related to the failure. – lcs Jun 24 '16 at 14:12
  • 7
    Please post a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Are you sure the file exists and is readable? – MikeCAT Jun 24 '16 at 14:13
  • 4
    So does the file exist in your current working directory? Do you have access rights for it? – πάντα ῥεῖ Jun 24 '16 at 14:13
  • 7
    I don't believe you. Add `printf("%p\n", fp)` somewhere. – Eugene Sh. Jun 24 '16 at 14:13
  • 1
    @EugeneSh. `printf("%p\n", (void*)fp)` is better. – MikeCAT Jun 24 '16 at 14:15
  • Are you looking at optimized code here? When the optimizer gets involved, variables are not always stored at the location the debug data says they are. – Ben Voigt Jun 24 '16 at 14:21
  • Possible duplicate of [opening a file with fopen](http://stackoverflow.com/questions/1746510/opening-a-file-with-fopen) – Cherubim Jun 24 '16 at 14:24
  • You wrote "in a function". I suggest some scope issue in your case. Can you post your function complete code? And a call to that function that you use. – Dmitry VS Jun 24 '16 at 14:25
  • 2
    Call `strerror` to get the error reason – lost_in_the_source Jun 24 '16 at 14:26
  • I would suggest to use un-optimizing compilation, and then add some printf() here and there. What you are saying is highly unlikely and would involve compiler bugs. – Jack Jun 24 '16 at 14:34
  • 1
    When a program is behaving in a way that makes no sense, it's very likely that the problem is not where you think it is. This is why we ask for a **complete program** that we can run ourselves and watch fail. You've posted a bunch of fragments, but if we attempt to reassemble them into a complete program we're probably going to get a different one from the one you have, and the difference might be enough to hide the problem. – zwol Jun 24 '16 at 14:47
  • The updated code is a mess.... – Eugene Sh. Jun 24 '16 at 14:53
  • It's the `printf("%p\n", fp);` prints the number, not the `perror`. the `if` is never entered, as predicted. So where is the problem now? – Eugene Sh. Jun 24 '16 at 14:54
  • ok, you say the if is never entered, but where does it stops then? Using the debugger i can clearly see the the program is not working anymore after the fopen. The program does not scan the file, so it stops before. – Rick Jun 24 '16 at 15:00
  • and again, sorry for my mess, it's my first question, how can i make the code neater for you? – Rick Jun 24 '16 at 15:01
  • @Rick It's your job to debug it. But clearly the original problem you have stated is not there. Yo can format the code properly as a coding style guides suggesting. – Eugene Sh. Jun 24 '16 at 15:02
  • I took your several fragments, added a dummy version of function `stampaRisultato()`, added `#include` directives for `stdlib.h` and `stdio.h`, and built the result. It does not exhibit the problem you describe. – John Bollinger Jun 24 '16 at 15:04
  • Your code *does* have errors; I noted in particular that function `leggiRisultati()` fails to write the number of records read in `*dim`, which will cause you trouble later. But I do not accept that a non-NULL `FILE *` is initially stored in variable `fp`, but `fp`'s value is found to be `NULL` in the next statement. – John Bollinger Jun 24 '16 at 15:08
  • @JohnBollinger so, how do you suggest to resolve the problem with fp's value that is found to be NULL? – Rick Jun 24 '16 at 15:14
  • but it is not found to be `NULL`! You have just proven it. – Eugene Sh. Jun 24 '16 at 15:16
  • @EugeneSh. I know i proved it, i wrote that in the question. The only way the program does not go on it's because that fp is = NULL. So my question remains, i can see that fp is not NULL, then why my program does go on? – Rick Jun 24 '16 at 15:19
  • Because you have other bugs, that you have to hunt! But not the one you have stated in the original question. I don't understand what is not clear. – Eugene Sh. Jun 24 '16 at 15:21
  • @Rick, if `fp` is ever `NULL` after the `fopen()` call and before the first `fscanf()` in the code you presented, then it is because `fopen()` returned `NULL`. That indicates a failure to open the file, which is a condition that you should check for routinely. It might be that the file is not present (where the program is looking for it) or that you do not have read access to it for one reason or another. Fix that as appropriate for the specific nature of the problem. – John Bollinger Jun 24 '16 at 15:40
  • Looking at your expanded code, I strongly suspect that `fopen` *is* succeeding, but the `while` loop never executes because the `fscanf` call is too brittle. [Never use any of the `scanf` functions](https://stackoverflow.com/questions/15664664/scanf-regex-c/15664816#15664816). Instead, read an entire line, with [`getline`](http://linux.die.net/man/3/getline) if possible, otherwise with [`fgets`](http://linux.die.net/man/3/fgets), parse it by hand (you may find `strtok`, `strspn`, `strchr`, etc helpful) and convert numeric strings with the `strtol`/`strtod` family. – zwol Jun 24 '16 at 15:40
  • (cont'd) Doing it that way *is* a lot more work upfront, but it forces you to think carefully about what the code should do if the input is not what you expect it to be, and it's infinitely easier to debug once you have the parser written. – zwol Jun 24 '16 at 15:41
  • @Rick, if `fp`'s value changes later in the code then it is a result of your program exhibiting undefined behavior. The most likely avenue I see for that is overrunning the bounds of `temp.nome` during the process of counting lines (because one of the entries in your file does not fit). – John Bollinger Jun 24 '16 at 15:42

1 Answers1

2

Your code should work, I can only think of 3 things that may cause this issue. In my experience, it's oftentimes the simplist mistakes that get you, because you're so focused on the more complex elements that some things slip your mind. I can't see the rest of your program, so forgive me if any of these answers seem patronizing. Here are the first things I would check:

1.) file permissions. Make sure you're a user with permission to access and/or change the file in question. This is a pretty easy fix on linux, but I don't know about windows.

2.) file location. Make sure your text file is in the same directory as your executable. You'll need to do this if you don't specify file location.

3.) #include statements. Sometimes even the best of us get too excited to get into the bulk of our program, and we forget to include stdio.h and/or stdlib.h. If this is the case you may run into an issue where you set the file pointer to null, and then the fopen function doesn't run, so your pointer remains null.

MacedonZero
  • 216
  • 1
  • 9
  • the code does not have errors, nor warnings.. theoretically should work, but it does not. – Rick Jun 24 '16 at 14:48
  • Had the same issue while running fopen() on Xcode, this answer helped point me in the right direction. Problem was solved using this answer: https://stackoverflow.com/questions/13531331/fopen-not-work-with-xcode – Hadi Mar 12 '19 at 16:07