在写入文件时,fprintf 不像 printf 吗?

Is fprintf not like printf when writing to file?

本文关键字:不像 printf fprintf 文件      更新时间:2023-10-16

我已经查看了文档:

它在这里说:

成功打开文件后,您可以使用 fscanf() 从中读取或使用 fprintf() 写入文件。这些功能只工作 像scanf()和printf(),除了它们需要一个额外的第一个 参数,一个用于要读取/写入的文件的文件 *。

因此,我这样编写了代码,并确保包含一个条件语句以确保文件打开:

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

做。为什么我们在哪里分配内存很重要?在这里查看我更详细的答案:链表附加中的指针指针

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