尝试将整数写入文件中生成C语言中的随机字符
我正在尝试用 C 语言制作随机 input.txt
文件生成器,但我不断在输出文件中获取随机字符。我尝试同时使用 putw() 和 fwrite() 但得到相同的结果。
for(int i = 0; i < 100; i++){
ran_numb = rand()%(ram_size-1);
// printf("%d", ran_numb);
// int err = putw(ran_numb, fp);
fwrite(&ran_numb, sizeof(int), 1, fp);
fputc('\n', fp);
}
输出文件:
~
ô
u
?
{
ø
È
Õ
å
×
¡
完整代码:
#include <stdio.h>
#include <string.h>
int main (int argc, char* argv){
generate_input_file(2048);
}
void generate_input_file(int ram_size){
int ran_numb = 0;
FILE *fp = fopen("input.txt", "w");;
if(fp == NULL){
printf("can't open file!");
}
for(int i = 0; i < 100; i++){
ran_numb = rand()%(ram_size-1);
// printf("%d", ran_numb);
// int err = putw(ran_numb, fp);
fwrite(&ran_numb, sizeof(int), 1, fp);
fputc('\n', fp);
}
}
I'm trying to make a random input.txt
file generator in C language
but I keep getting random characters in the output file. I tried using both putw()
and fwrite()
but I get the same result.
for(int i = 0; i < 100; i++){
ran_numb = rand()%(ram_size-1);
// printf("%d", ran_numb);
// int err = putw(ran_numb, fp);
fwrite(&ran_numb, sizeof(int), 1, fp);
fputc('\n', fp);
}
output file:
~
ô
u
?
{
ø
È
Õ
å
×
¡
full code:
#include <stdio.h>
#include <string.h>
int main (int argc, char* argv){
generate_input_file(2048);
}
void generate_input_file(int ram_size){
int ran_numb = 0;
FILE *fp = fopen("input.txt", "w");;
if(fp == NULL){
printf("can't open file!");
}
for(int i = 0; i < 100; i++){
ran_numb = rand()%(ram_size-1);
// printf("%d", ran_numb);
// int err = putw(ran_numb, fp);
fwrite(&ran_numb, sizeof(int), 1, fp);
fputc('\n', fp);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在评论的帮助下,这是最终的程序:
我添加了缺少的标题以停止警告。
After the help of the comments, this is the final program:
I've added the missing headers to stop warnings.