[問題] 檔案處理
看板C_and_CPP作者Ryan45758 (☺000Qryan45758)時間5年前 (2018/12/03 20:36)推噓3(3推 0噓 11→)留言14則, 4人參與討論串2/2 (看更多)
編譯軟體 : 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
推
12/04 00:25,
5年前
, 1F
12/04 00:25, 1F
瞭解了 感謝
推
12/04 01:04,
5年前
, 2F
12/04 01:04, 2F
→
12/04 01:04,
5年前
, 3F
12/04 01:04, 3F
測試後還真的是超過100就不行了 我再去試看看 感謝
→
12/04 02:49,
5年前
, 4F
12/04 02:49, 4F
→
12/04 02:50,
5年前
, 5F
12/04 02:50, 5F
→
12/04 02:52,
5年前
, 6F
12/04 02:52, 6F
好的 我會再去摸索看看 因為有些課本還沒提到
→
12/04 02:52,
5年前
, 7F
12/04 02:52, 7F
→
12/04 04:16,
5年前
, 8F
12/04 04:16, 8F
→
12/04 04:17,
5年前
, 9F
12/04 04:17, 9F
→
12/04 04:21,
5年前
, 10F
12/04 04:21, 10F
※ 編輯: 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
推
12/04 05:11,
5年前
, 11F
12/04 05:11, 11F
→
12/04 05:11,
5年前
, 12F
12/04 05:11, 12F
→
12/04 05:21,
5年前
, 13F
12/04 05:21, 13F
→
12/04 05:21,
5年前
, 14F
12/04 05:21, 14F
討論串 (同標題文章)