[問題] 檔案處理

看板C_and_CPP作者 (☺000Qryan45758)時間5年前 (2018/12/03 20:36), 5年前編輯推噓3(3011)
留言14則, 4人參與, 5年前最新討論串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
str的部分是write要用的buffer
12/04 00:25, 1F
瞭解了 感謝

12/04 01:04, 5年前 , 2F
第二個應該是因為你的緩衝區只有3 只要取到百位以上 沒地
12/04 01:04, 2F

12/04 01:04, 5年前 , 3F
方放\n 就會越界了?
12/04 01:04, 3F
測試後還真的是超過100就不行了 我再去試看看 感謝

12/04 02:49, 5年前 , 4F
雖然不知道你是怎麼編譯過的, 不過這邊用 stdio.h 裡的函
12/04 02:49, 4F

12/04 02:50, 5年前 , 5F
式會簡單得多, 格式化輸出用 fprintf() 非格式化輸出用
12/04 02:50, 5F

12/04 02:52, 5年前 , 6F
fwrite(), 這邊完全不需要轉換成字串, 學會前面提到的兩個
12/04 02:52, 6F
好的 我會再去摸索看看 因為有些課本還沒提到

12/04 02:52, 5年前 , 7F
函式即可
12/04 02:52, 7F

12/04 04:16, 5年前 , 8F
https://godbolt.org/z/aZ-lv0 初學教的應該只是簡單的
12/04 04:16, 8F

12/04 04:17, 5年前 , 9F
file I/O, 不太可能用到 <fcntl.h>
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
建議strcpy改成strncpy 多的一個參數放sizeof(str)-1 留
12/04 05:11, 11F

12/04 05:11, 5年前 , 12F
最後一個位子放\n
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
文章代碼(AID): #1S1ICtO0 (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1S1ICtO0 (C_and_CPP)