在写入文件时,fprintf 不像 printf 吗?
Is fprintf not like printf when writing to file?
我已经查看了文档:
它在这里说:
成功打开文件后,您可以使用 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()
未 正确实现。
在
from_user()
中创建的指针不会传递回调用函数。为此,您需要一个双指针,或者通过引用传递。在您的代码中,您将
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 中分配内存并将指针传递给你的函数,如下所示:
- 删除
b = malloc(10);
- 删除 scanf 中 b 之前的
&
- 将
int*ch = NULL;
更改为int *ch = malloc(sizeof(int));
做。为什么我们在哪里分配内存很重要?在这里查看我更详细的答案:链表附加中的指针指针
哦,你应该把free(ch)
从 else 语句中移出。
相关文章:
- 使用wchar_t更改字符的类型不像L
- 为什么 const YAML::Node 对象的行为不像 yaml-cpp 中的类似值的对象?
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类
- 为什么当"::"的行为不像运算符时被称为'scope resolution operator'?
- C++中的后缀不像我期望的那样表现
- std::设置扣除指南不像我期望的那样工作
- 为什么具有单独字符的字符数组不像字符串文字那样以 null 终止符结尾?
- 多线程不像预期的那样行动
- 为什么“reinterpret_cast”的行为不像C++标准所说的那样
- 我的老师不像其他人那样进行类型转换.有谁知道他在做什么?
- 使用OpenGL显示两个对象.纹理不像预期的那样行为
- 为什么行为 std::chrono::d uration::operator*= 不像内置的 *=?
- 为什么 boost::p rogram_options::bool_switch 的行为不像我预期的那样
- C muparser解析的行为不像预期的那样
- 为什么获得的 MachineGuid 看起来不像 GUID,而是像韩语?
- C 矢量的表现不像我想象的那样直观
- 为什么这段代码不像我想的那样工作
- 在写入文件时,fprintf 不像 printf 吗?
- 可以放置新的生存优化,不像内存集
- C++ 向量不像数组