Home > database >  Why my void function from another file is not running in this C program?
Why my void function from another file is not running in this C program?

Time:10-27

I want to print the content of a txt file (first parameter), but the function to do so is in a different file. I have the following main file:

#include <stdio.h>
#include <stdlib.h> 
#include <string.h>
#include "fileoperation.h"

int main(int argc, char **argv)
{
  read(argv[1]);  
    
  return 0;
}

and then in the fileoperation.c file I have:

#include "fileoperation.h"

void read(char* file)
{
  FILE *fptr;
  char c;
  fptr = fopen(file, "r");
  if (fptr == NULL)
  {
    printf("Cannot open file \n");
    exit(0);
  }

  c = fgetc(fptr);
  while (c != EOF)
  {
    printf ("%c", c);
    c = fgetc(fptr);
  }
  
  fclose(fptr);

}

If I type the code from the function in the main function, it works. I don't understand why is not working

The header file of fileoperation.c is

#ifndef FILEOPERATION_H
#define FILEOPERATION_H
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h> 
#include <string.h>

void read(char* file);

#endif

CodePudding user response:

Rename your function. read exists in the backing libraries. To make matters worse, the compiler knows what it does and optimizes it out.

Could have been worse. You could have replaced the actual read with your own and blown up the standard libraries.

CodePudding user response:

You appear to be using a non-standard compiler, or you have configured it incorrectly. Compilers like gcc and clang are known to invoke non-compliant behavior unless you compile with -std=c17 -pedantic-errors (see What compiler options are recommended for beginners learning C?). I cannot reproduce the problem using a C compliant compiler.

A compliant compiler is not allowed to place non-standard identifiers in standard headers other than those explicitly reserved by the C standard. Examples of reserved identifiers are those with two leading underscores, those with a leading underscore followed by an upper-case letter and identifiers reserved for future language/library extensions. Source: ISO 9899:2018 chapters 4/6, 7.1.3, 6.11 and 7.31.

The mentioned compilers should remove all non-standard identifier declarations when compiling in C language compliant mode as described above. If it doesn't, you have found a compiler library bug.

There exists an old, well-known (and incredibly poorly named) function read, but it has never been part of the standard C library. (POSIX tried to standardize it but that's irrelevant here.) So the easy solution is to simply not name an identifier read - not so much because a well-known non-standard function has that name, but because it is a very poor and non-descriptive identifier name. In your case you could have used read_file or similar.

  • Related