問題描述
使用 putw() 時在文件中獲取亂碼 (Getting gibberish values in files when putw() is used)
程序從用戶那裡獲取整數輸入並將它們存儲在一個文件中,然後將整數排序到兩個不同的文件(奇數和偶數)中,當我使用 fprintf 時,它會覆蓋以前的值,這就是我嘗試 putw() 的原因,但我是在文件中獲取亂碼值
這是我的代碼:
#include<stdio.h>
int main()
{
int n,a[50];
printf("\nEnter no of entries:");
scanf("%d",&n);
FILE *f1,*f2,*f3;
f1=fopen("Numbers.txt","w+");
for(int i=0;i<n;i++)
{
printf("\nEnter a number:");
scanf("%d",&a[i]);
putw(a[i],f1);
}
fclose(f1);
f1=fopen("Numbers.txt","r");
for(int i=0;i<n;i++)
{
if(a[i]%2==0)
{
f2=fopen("EvenNum.txt","w+");
putw(a[i],f2);
fclose(f2);
}
else
{
f3=fopen("OddNum.txt","w+");
putw(a[i],f3);
fclose(f2);
}
}
}
參考解法
方法 1:
That's not what putw
does. putw
writes an int
in binary not as text. Do you mean fprintf(f1, "%d", a[i]);
?
The man page for getw
and putw
says to use fread
and fwrite
instead, which doesn't seem to fit here.
f1=fopen("Numbers.txt","w+");
will clobber the file. Do you want "a+"
to append?
(by Chaitanya Nirfarake、Joshua)