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

Offline sardegnagranata

  • Single posting newcomer
  • *
  • Posts: 1
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

  • Lives here!
  • ****
  • Posts: 574
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: 581
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 10 64 bits (20.04), svn C::B (last version or almost!), wxWidgets 3.1.4, Msys2 Compilers 10.2.0, 64 bits (seh, posix : gcc, g++ and gfortran in C:\msys64\mingw64) or 32 bits (sjlj, posix in C:\msys64\mingw32).