使用 putw() 時在文件中獲取亂碼 (Getting gibberish values in files when putw() is used)


問題描述

使用 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 NirfarakeJoshua)

參考文件

  1. Getting gibberish values in files when putw() is used (CC BY‑SA 2.5/3.0/4.0)

#file-handling #C






相關問題

c語言使用文件操作創建數據庫 (Create database using file operation in c language)

使用jsp瀏覽文件和文件夾 (browsing files and folders using jsp)

在 rails/paperclip 中處理一系列圖像 (handling an array of images in rails/paperclip)

Java 並行文件處理 (Java Parallel File Processing)

Perl 隱式關閉重置 $. 多變的 (Perl implicit close resets the $. variable)

更換和存放 (Replacing and Storing)

逐行讀取文件並基於它將換行符寫入同一文件 - nodejs (Reading a file line by line and based on it write newlines to same file - nodejs)

使用 PHP 將數據放到服務器上(新的 DOMdocument 不起作用) (Use PHP to put data onto server ( new DOMdocument not working))

表示“目錄”或“文件”的詞是什麼? (What is the word that means "directory" or "file"?)

如何在我的計算機上保存我用 Python 編輯的 CSV 文件? (How do I save a CSV file on my computer which i have edited in Python?)

使用文件中的類和對象獲取信息 (Get info using class and object from file)

使用 putw() 時在文件中獲取亂碼 (Getting gibberish values in files when putw() is used)







留言討論