Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

modularity

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

like image 911
carreramcl Avatar asked Mar 02 '23 10:03

carreramcl


1 Answers

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.

like image 120
Joshua Avatar answered Mar 03 '23 23:03

Joshua