试图将整数写入文件会在 C 语言中生成随机字符

trying to write integers into file genreates random characters in C language

我正在尝试在 C language 中创建一个随机 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);
    }


}

经过大家的帮助,这是最终的程序:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>

#include "simulator.h"

int main (int argc, char* argv){
    generate_input_file(2048);
}

void  Gen_Input_File(int ram_size){
    int ran_numb = 0;
    const char filename[] = "input.txt"

    FILE *fp = fopen(filename, "w");;
    if(fp == NULL){
        fprintf(stderr, "Failed to open file '%s' for writing: %s\n", filename, strerror(errno));
        exit(EXIT_FAILURE);
    }

    srand(time(NULL));
    for(int i = 0; i < 10000; i++){
        ran_numb = rand()%(ram_size-1);
        fprintf(fp, "%d\n", ran_numb);
    }

}

我添加了缺失的 headers 以停止警告。