写入文件时 fprintf 不像 printf 吗?

Is fprintf not like printf when writing to file?

我已查看文档:

它说 here:

Once a file has been successfully opened, you can read from it using fscanf() or write to it using fprintf(). These functions work just like scanf() and printf(), except they require an extra first parameter, a FILE * for the file to be read/written.

所以,我就这样写了我的代码,并且确保包含一个条件语句以确保文件打开:

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

void from_user(int*b){

    b = malloc(10);
    printf("please give me an integer");
    scanf("%d",&b);

}

void main(){

    FILE *fp;

    int*ch = NULL;
    from_user(ch);
    fp = fopen("bfile.txt","w");

    if (fp == NULL){
        printf("the file did not open");
    }
    else {
        printf("this is what you entered %d",*ch);
        fprintf(fp,"%d",*ch);  
        fclose(fp);
        free(ch);   
    }
}

是我错了还是文档解释不正确?谢谢。

from_user() 未正确实施。

  1. 您在 from_user() 中创建的指针不会传回调用函数。为此,您需要一个双指针,或者通过引用传递。

  2. 在您的代码中,您将 int ** 传递给 scanf(),而它期望变量为 int *

这是一个有效的实现:

void from_user(int **b){
    *b = malloc(sizeof(int));
    printf("please give me an integer");
    scanf("%d", *b);
}

int main() {
    int *ch;
    from_user(&ch);
}

你的文件 IO

那部分没问题。只是 ch 的值被破坏了。

更简单的from_user实现

int from_user(){
    int i;
    printf("please give me an integer");
    scanf("%d", &i);
    return i;
}

并在主要部分

int ch = from_user();
...
      printf("this is what you entered %d",ch);
        fprintf(fp,"%d",ch);  

最简单的修复你自己的代码,你不需要使用双指针,只需在 main 中分配内存并将指针传递给你的函数,就像这样:

  1. 删除b = malloc(10);
  2. 去掉scanf中b前面的&
  3. int*ch = NULL;更改为int *ch = malloc(sizeof(int));

完成。为什么在何处分配内存很重要?在这里查看我更详细的答案:pointer of a pointer in linked list append

哦,你应该从 else 语句中移出 free(ch)