为什么另一个文件中的 void 函数没有在此 C 程序中运行?

car*_*mcl 4 c modularity

我想打印 txt 文件的内容(第一个参数),但执行此操作的函数位于不同的文件中。我有以下主文件:

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

int main(int argc, char **argv)
{
  read(argv[1]);  
    
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

然后在 fileoperation.c 文件中我有:

#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);

}
Run Code Online (Sandbox Code Playgroud)

如果我在主函数中键入函数中的代码,它就会起作用。我不明白为什么不工作

fileoperation.c的头文件是

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

void read(char* file);

#endif

Run Code Online (Sandbox Code Playgroud)

Jos*_*hua 7

重命名您的函数。read存在于支持库中。更糟糕的是,编译器知道它的作用并对其进行优化。

情况可能会更糟。您可以用自己的代码替换实际的代码read并炸毁标准库。