Can*_*ic3 -2 c c++ linux file-io printf
我查看了文档:
它在这里说:
成功打开文件后,您可以使用fscanf()从中读取文件或使用fprintf()写入文件.这些函数就像scanf()和printf()一样工作,除了它们需要一个额外的第一个参数,一个FILE*用于读/写文件.
所以,我这样编写了我的代码,并确保包含一个条件语句以确保文件打开:
# 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我错了还是文档没有正确解释?谢谢.
from_user() 未正确实施.您创建的指针from_user()将不会传递回调用函数.为此,您需要一个双指针,或通过引用传递.
在你的代码中,你传递一个int **to 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);
}
Run Code Online (Sandbox Code Playgroud)
那部分都很好.只是它的价值ch被打破了.