作者Ryan45758 (☺000Qryan45758)
看板C_and_CPP
標題[問題] 檔案處理
時間Mon Dec 3 20:36:03 2018
編譯軟體 : Dev C++
問題一 :
試產生10個1~16之間的整數亂數,並將它寫入二進位檔"rand.bin"中。
問題一程式碼:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <io.h>
#include <sys/stat.h>
int main(void)
{
int i,rnd;
int f1;
char str[3];
f1=creat("C:\\Users\\ryan4\\Desktop\\習題選答\\chap12\\hw12_16\\rand.bin",O_CREAT|O_WRONLY|O_BINARY);
if(f1!=-1)
{
for(i=0;i<10;i++)
{
rnd=rand()%16+1;
strcpy(str,itoa(rnd,str,10));
write(f1,str,sizeof(str));
}
close(f1);
printf("檔案寫入完成!!\n");
}
else
printf("檔案開啟失敗!!\n");
system("pause");
return 0;
}
執行結果:
10 4 15 5 2 13 7 15 3 1
想請問char str[3]是什麼意思
問題二 : 修改上述程式碼,產生50個1~1000的整數亂數,並將它寫入純文字檔"rand.txt"中。
程式碼 :
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <io.h>
#include <sys/stat.h>
int main(void)
{
int i,rnd;
int f1;
char str[3];
f1=creat("C:\\Users\\ryan4\\Desktop\\習題選答\\chap12\\hw12_16\\rand.txt",O_CREAT|O_WRONLY|O_TEXT);
if(f1!=-1)
{
for(i=0;i<
50;i++)
{
rnd=rand()%
1000+1;
strcpy(str,itoa(rnd,str,10));
write(f1,str,sizeof(str));
}
close(f1);
printf("檔案寫入完成!!\n");
}
else
printf("檔案開啟失敗!!\n");
system("pause");
return 0;
}
執行的錯誤結果:
名代眝W﹋鵄瞰
想請問為什麼會變一坨亂碼呢?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.200.47.155
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1543840567.A.600.html
推 jianda1996: str的部分是write要用的buffer 12/04 00:25
瞭解了 感謝
推 mmmmei: 第二個應該是因為你的緩衝區只有3 只要取到百位以上 沒地 12/04 01:04
→ mmmmei: 方放\n 就會越界了? 12/04 01:04
測試後還真的是超過100就不行了 我再去試看看 感謝
→ poyenc: 雖然不知道你是怎麼編譯過的, 不過這邊用 stdio.h 裡的函 12/04 02:49
→ poyenc: 式會簡單得多, 格式化輸出用 fprintf() 非格式化輸出用 12/04 02:50
→ poyenc: fwrite(), 這邊完全不需要轉換成字串, 學會前面提到的兩個 12/04 02:52
好的 我會再去摸索看看 因為有些課本還沒提到
→ poyenc: 函式即可 12/04 02:52
→ poyenc: file I/O, 不太可能用到 <fcntl.h> 12/04 04:17
※ 編輯: Ryan45758 (1.200.47.155), 12/04/2018 04:47:08
※ 編輯: Ryan45758 (1.200.47.155), 12/04/2018 04:48:36
※ 編輯: Ryan45758 (1.200.47.155), 12/04/2018 04:59:42
推 mmmmei: 建議strcpy改成strncpy 多的一個參數放sizeof(str)-1 留 12/04 05:11
→ mmmmei: 最後一個位子放\n 12/04 05:11
→ loveme00835: 你再好好思考一下”寫二進位檔”是什麼意思, 不會就 12/04 05:21
→ loveme00835: 問老師或助教 12/04 05:21