PTT
Submit
Submit
选择语言
正體中文
简体中文
PTT
C_and_CPP
[问题] 档案处理(已解决)
楼主:
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
你再好好思考一下”写二进制档”是什么意思, 不会就问老师或助教
继续阅读
[问题] C++ template 确定函式是否存在
mikukonn
Re: [问题] 九九乘法表不用循环是叫我直接从1列到81?
firejox
Re: 关于 stl 和 c++ 的一点问题
firejox
Re: [问题] vector<int>& nums 和vector<int>* vec
poyenc
Re: [问题] 九九乘法表不用循环是叫我直接从1列到81?
poyenc
Re: 关于 stl 和 c++ 的一点问题
poyenc
[问题]OpenCV imshow函式问题
Eligor41
[问题] break while后 while仍持续进行条件判断
nthulibrary
[问题] 资料结构的问题
SWTSunny
[问题] vector<int>& nums 和vector<int>* vec
s505015
Links
booklink
Contact Us: admin [ a t ] ucptt.com