"参数无效"在创建文件时

时间:2018-01-09 23:38:39

标签: c file

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

使用库errno.hextern int errno我得到了#34;错误的值:22"。

if (!fp)perror("fopen")给了我"错误打开文件:无效的参数"。

在我的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 个答案:

答案 0 :(得分: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?

2。 fflush(stdin)的行为未定义。见Using fflush(stdin)fflush输出缓冲区一起使用,它告诉操作系统应该写入 缓冲的内容。 stdin输入缓冲区,刷新没有任何意义。

3。 像这样使用fgets

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

使用sizeof name_file更加强大,因为这将永远为您提供帮助 正确的尺寸。如果您稍后将name_file的声明更改为 一个少于30个空格的char数组,但忘记更改fgets中的size参数 可能最终会出现缓冲区溢出。

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

5。 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;
相关问题