首页 文章

创建文件时“无效参数”

提问于
浏览
-1

你能帮我创建一个文本文件,因为现在指向文件的* fp指针会向函数fopen返回NULL吗?

使用库 errno.hextern int errno 我得到"Value of errno: 22" .

if (!fp)perror("fopen") 给了我"Error opening file: Invalid argument" .

在我的main函数中,我输入文件的名称:

void main()
{
    float **x;
    int i,j;
    int l,c;
    char name_file[30];
    FILE *res;

    /* some lines omitted */

    printf("\nEnter the name of the file =>"); 
    fflush (stdin);
    fgets(name_file,30,stdin);
    printf("Name of file : %s", name_file);

    res=creation(name_file,l,c,x);
    printf("\nThe created file\n");
    readfile(res,name_file);
}

创建文本文件的功能:

FILE *creation(char *f_name,int l, int c, float **a) // l rows - c colums - a array 
{   FILE *fp;
    int i,j;

    fp = fopen(f_name,"wt+"); // create for writing and reading

    fflush(stdin);

/* The pointer to the file is NULL: */

    if (!fp)perror("fopen"); // it's returning Invalid argument
    printf("%d\n",fp); //0 ??

    if(fp==NULL) { printf("File could not be created!\n"); exit(1); }

    fflush(stdin);
    for(i=0;i<l;i++)
  {
     for(j=0;j<c;j++)
     {
        fprintf(fp,"%3.2f",a[i][j]); // enter every score of the array in the text file
     }
     fprintf(fp,"\n");
  }

    return fp;
}

读取文件并检查文件是否正确的功能:

**void readfile(FILE *fp,char *f_name)**
{
  float a;
  rewind(fp);
  if(fp==NULL) { printf("File %s could not open\n",f_name); exit(1); }
  while(fscanf(fp,"%3.2f",&a)!= EOF)
    printf("\n%3.2f",a);
  fclose(fp);
}

1 回答

  • 1

    你的代码有很多错误的东西 .

    1. main 的正确签名是
    • int main(void);

    • int main(int argc, char **argv)

    • int main(int argc, char *argv[])

    What are the valid signatures for C's main() function?

    1. fflush(stdin) 的行为未定义 . 见Using fflush(stdin) . fflushoutput 缓冲区一起使用,它告诉OS应该写入缓冲内容 . stdin 是一个 input 缓冲区,刷新没有任何意义 .

    3.像这样使用 fgets

    char name_file[30];
    fgets(name_file, sizeof name_file, stdin);
    

    它使用 sizeof name_file 更强大,因为这将为您提供始终正确的大小 . 如果稍后将 name_file 的声明更改为少于30个空格的 char 数组,但忘记更改 fgets 中的size参数,则最终可能会出现缓冲区溢出 .

    你正在向 creation 传递指向无处的未初始化指针 p . 在所述函数中,您无法使用指针 a 进行读取或写入 . 您需要在调用 creation 之前分配内存 . 至少从您发布的代码判断 .

    1. fgets 保留换行符( '\n' ),因此 name_file 包含换行符 . 无论如何,我真的不想让你的文件名中有换行符 . 最好在将它传递给 fopen 之前将其删除(这可能是错误22的原因):
    char name_file[30];
    fgets(name_file, sizeof name_file, stdin);
    int len = strlen(name_file);
    if(name_file[len - 1] == '\n')
        name_file[len - 1] = 0;
    

相关问题