将文件名传递给函数

Passing file name to function

我必须填充两个表示点坐标的数组,然后将它们存储到一个文件中。

这里我没有把刚才提到的所有代码都写出来,我必须尊重函数参数的格式save_file,但是这里我遇到了一个问题:我应该如何传递参数文件功能? fptr是文件名吗?还有我应该如何在函数内部使用参数,因为当我 运行 程序时,我收到以下警告:

incompatible pointer types passing 'char *' to parameter of type 'FILE *' (aka 'struct _IO_FILE *') passing argument to parameter '__stream'

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

int main(void)
{
 float *xi;
 float *yi;
 FILE * fptr = NULL;
 fptr = fopen("xypoint.dat","w");
 save_file("xypoint.dat",xi,yi);
 fcose(fptr);
 return 0;

}

void save_file(char * myfilename, double * xinterp, double * yinterp)
{
  int n=4;
  while( n-- > 0 )
  {
    fprintf(myfilename,"%.3f  %.3f\n",*(xinterp++),*(yinterp++));
  }
}

你可能想要这个:

...
int main(void)
{
  float *xi;
  float *yi;
  // you need to initialize xi and yi, but I supposed
  // you omitted this for brevity
  save_file("xypoint.dat", xi, yi);
  return 0;
}

void save_file(char *myfilename, double *xinterp, double *yinterp)
{
  FILE *fptr = fopen(myfilename, "w");
  // no error checking for brevity

  for (int i = 0; i < 4; i++)  // use for here, it shows the intention clearly
  {
    fprintf(fptr, "%.3f  %.3f\n", xinterp[i], yinterp[i]);  // use [] here,
                                                            // it's more readable
  }

  fclose(fptr);
}

请注意 incompatible pointer types ... 警告与其说是警告,不如说是错误。

您必须决定 open/close 文件在 save_file 函数内部还是外部。

如果您在 函数 中打开文件 save_file, 您传递 文件名 ,其类型为 char *.

int main(void)
{
  // ...
  save_file("xypoint.dat", xi, yi); // pass FILENAME to save_file
}

void save_file(char *myfilename, double *xinterp, double *yinterp)
{
  FILE *fptr = fopen(myfilename, "w"); // open file INSIDE save_file
  
  // write the file
  for (int i = 0; i < 4; i++)
  {
    // use `fptr`(the return value from fopen), not `myfilename`
    fprintf(fptr, "%.3f  %.3f\n", xinterp[i], yinterp[i]);
  }

  fclose(fptr); // close file INSIDE save_file
}

如果您在外部 save_file 函数中打开文件, 您传递 打开的文件结构指针 ,其类型为 FILE *.

int main(void)
{
  // ...
  FILE *fptr = fopen("xypoint.dat", "w"); // open file OUTSIDE save_file
  save_file(fptr, xi, yi); // pass FILE* to save_file
  fclose(fptr); // close file OUTSIDE save_file
}

void save_file(FILE *fptr, double *xinterp, double *yinterp)
{
  // no need to open file again
  
  // write the file
  for (int i = 0; i < 4; i++)
  {
    // use `fptr` directly
    fprintf(fptr, "%.3f  %.3f\n", xinterp[i], yinterp[i]);
  }

  // no need to close file here
}