Reputation: 79
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. 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);
}
Upvotes: 0
Views: 241
Reputation: 223699
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, i.e. either 0 or 1, is assigned to f
. So f
doesn't point to a valid location, and that is why your fprintf
calls fail. 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
. 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(f);
fgets(s,sizeof(s),f);
puts(s);
printf("\n");
rewind(b);
fgets(s,sizeof(s),b);
puts(s);
printf("\n");
Upvotes: 3