Author Topic: opening a text file in C by using Code Blocks - cannot open the file  (Read 9298 times)

sardegnagranata

  • Guest
Hello, I'm trying to use codeblocks to open a text file in C. I can't open the text file, the text file is placed in the directory where the 4DE_file.c is placed. This is the C code:

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

int main() {
    FILE *puntaFile;
    char c;
    puntaFile=fopen("nomi.txt","r");
    if(puntaFile != NULL) {
      printf("sono dentro!");
      c = fgetc(puntaFile);
      while(c != EOF)
      {
         putchar(c);
         c=fgetc(puntaFile);
      }
      fclose(puntaFile);
    }
    else {
      printf("the file can't be opened !");
      return 1;
    }
}


The output I get is:    "the file can't be opened".

Is there any particular configuaration I should do before using files ?

Offline Miguel Gimenez

  • Developer
  • Lives here!
  • *****
  • Posts: 1553
Re: opening a text file in C by using Code Blocks - cannot open the file
« Reply #1 on: November 17, 2020, 06:18:38 pm »
The file must be in the working directory, and you can specify it using Project -> Properties -> Build targets -> Execution working dir. The default value is ".\", indicating the directory where the .CBP file resides.

Offline gd_on

  • Lives here!
  • ****
  • Posts: 796
Re: opening a text file in C by using Code Blocks - cannot open the file
« Reply #2 on: November 17, 2020, 07:07:56 pm »
More, ...
if you want to use your program outside Code::Blocks, for example directly in your bin subdirectory, you must have a copy of this text file where your executable has been created (as is written your code).
« Last Edit: November 17, 2020, 07:13:10 pm by gd_on »
Windows 11 64 bits (23H2), svn C::B (last version or almost!), wxWidgets 3.2.4 (tests with 3.3), Msys2 Compilers 13.2.0, 64 bits (seh, posix : gcc, g++ and gfortran in C:\msys64\mingw64) or 32 bits (dwarf2, posix  in C:\msys64\mingw32).