#include <stdio.h>
main()
{
         FILE*fp ;

   if   ((fp = fopen("new.txt","r")) == NULL);


   {
            printf("file could not be opened\n");
    return 0;

   }
}

this is what ive written and it always comes back with file could not be opened. I need to read the text file new, which has 10 variables separated by spaces in it.

You can get more information by printing the error message with perror():

if ((fp = fopen("new.txt", "r")) == NULL) {
    perror("Error opening new.txt");

    ...
}

But I notice that you have a rogue semicolon after the condition of your if statement, which means that the printf and return will always execute. If you copy pasted your exact code then that's the problem. Otherwise, a common issue is that the file isn't in your current working directory, which is where fopen() looks.

Edited 4 Years Ago by deceptikon

so, how do I put it into my current working directory

I'd do it with trial and error since there aren't many options, but an excellent start is the same directory as the executable file. Was the rogue semicolon not present in your actual code?

yes, It is present in the directory where the executable and object file are present (where you save your program).
and, as deceptikon told you, semi colon is the problem.
Program displays "File could not be opened" because the file is not there,

for reading the file "new", you first need to create the file using write mode i.e "w" instead of "r". Now, write the values as desired in the file using fprintf().
close the file using fclose() after writing the values.
and now finally, you can open the file in read mode "r" to read the values you have stored.

I've explained you the procedure! you just need to type the code.. :)

Edited 4 Years Ago by Vish0203

can you try this ? or strtol, please say if works

while(fscanf(f,"%d",&value) == 1)
{
/* do something with the value */
}
This article has been dead for over six months. Start a new discussion instead.