[問題] 檔案處理(已解決)

作者: Ryan45758 (阿郭)   2018-12-03 20:36:03
編譯軟體 : 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﹋鵄瞰
想請問為什麼會變一坨亂碼呢?
作者: jianda1996 (南無兩光有手槍)   2018-12-04 00:25:00
str的部分是write要用的buffer
作者: mmmmei (mmm煤)   2018-12-04 01:04:00
第二個應該是因為你的緩衝區只有3 只要取到百位以上 沒地方放\n 就會越界了?
作者: poyenc (髮箍)   2018-12-04 02:49:00
雖然不知道你是怎麼編譯過的, 不過這邊用 stdio.h 裡的函式會簡單得多, 格式化輸出用 fprintf() 非格式化輸出用fwrite(), 這邊完全不需要轉換成字串, 學會前面提到的兩個函式即可https://godbolt.org/z/aZ-lv0 初學教的應該只是簡單的file I/O, 不太可能用到 <fcntl.h>https://godbolt.org/z/7qQkSg 忘記 return :p
作者: mmmmei (mmm煤)   2018-12-04 05:11:00
建議strcpy改成strncpy 多的一個參數放sizeof(str)-1 留最後一個位子放\n
作者: loveme00835 (髮箍)   2018-12-04 05:21:00
你再好好思考一下”寫二進位檔”是什麼意思, 不會就問老師或助教

Links booklink

Contact Us: admin [ a t ] ucptt.com