[英]Fprintf doesnt write array to file
I have a code which should read an array, write it to a binary and to a text file, then print the files. 我有一个代码,应该读取一个数组,将其写入二进制文件和文本文件,然后打印文件。 However, the fprintf function returns an error and i have no idea why.
但是,fprintf函数返回错误,我不知道为什么。 This is my code :
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *f,*b;
if (f=fopen("fis.txt","w+")==NULL) {
printf ("Error\n");
exit(1);
}
if(b=fopen("binar.txt","w+b")==NULL) {
printf ("Error\n");
exit(1);
}
float *v; int n;
char s[1000];
scanf("%d",&n);
v=malloc(n*sizeof(float));
int x,y;
for (int i=0;i<=n;i++) {
scanf("%f",&v[i]);
printf("%f",v[i]);
x=fprintf(f,"%f",v[i]);
if (x<0) printf("err\n");
y=fprintf(b,"%f",v[i]);
if (y<0) printf ("err2\n");
}
fgets(s,sizeof(s),f);
puts(s);
printf("\n");
fgets(s,sizeof(s),b);
puts(s);
printf("\n");
free(v);
fclose(f);
fclose(b);
}
The main issue is how you're opening the files: 主要问题是如何打开文件:
if (f=fopen("fis.txt","w+")==NULL) {
The equality operator ==
has higher precedence than the assignment operator =
. 等价运算符
==
优先级高于赋值运算符=
优先级。 So first the result of fopen
is compared to NULL, then the result of that comparison, ie either 0 or 1, is assigned to f
. 因此,首先将
fopen
的结果与NULL比较,然后将该比较的结果(即0或1)分配给f
。 So f
doesn't point to a valid location, and that is why your fprintf
calls fail. 因此
f
不能指向有效位置,这就是为什么fprintf
调用失败的原因。 If you have warnings turned up on your compiler, it should have warned about assigning an integer to a pointer. 如果您的编译器出现警告,则应该警告您将整数分配给指针。
Add parenthesis to get the proper ordering: 添加括号以获得正确的顺序:
if ((f=fopen("fis.txt","w+"))==NULL) {
And: 和:
if ((b=fopen("binar.txt","w+b"))==NULL) {
Also, your loop condition is incorrect: 另外,您的循环条件不正确:
for (int i=0;i<=n;i++) {
The array v
has n
elements, meaning its indexes go from 0
to n-1
, but you loop from 0
to n
. 数组
v
具有n
元素,这意味着其索引从0
到n-1
,但是从0
到n
循环。 Change the loop condition to account for this: 更改循环条件以解决此问题:
for (int i=0;i<n;i++) {
You also need to call rewind
on each file descriptor before reading back from them so that you can read what you just wrote: 您还需要在
rewind
读每个文件描述符之前对每个文件描述符调用rewind
,以便您可以阅读刚刚编写的内容:
rewind(f);
fgets(s,sizeof(s),f);
puts(s);
printf("\n");
rewind(b);
fgets(s,sizeof(s),b);
puts(s);
printf("\n");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.