請教C如何写入及读取档案

 

各位大老
小弟想要把data存到txt里面但是不知道是哪里出错了下方是我打的代码及题目 拜托请各位帮我指正 感谢

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

int main(void)
{

    int  i, num, black = 0, white = 0, red = 0;
    int a, b;

    FILE* fp;
    fp = fopen("C:\Users\ASUS\Desktop\data.txt", "wb");
    if (fp != NULL)
    {
        for (a = 0; a <= 1; a++)
        {
            fprintf(fp, "%d%d%d", black, white, red);

        }
    }
    else
    {  printf("file can't open");
        exit(0);

    }
    fclose(fp);
   

    srand(time(NULL));

    for (i = 0; i < 10000; i++)
    {
        num = rand() % 10 + 1;

        if (num <= 5)
            ++black;

        if (5 < num && num <= 8)
            ++white;

        if (8 < num)
            ++red;
    }

    printf("出現黑球的次數為%d次\n", black);
    printf("出現白球的次數為%d次\n", white);
    printf("出現紅球的次數為%d次\n", red);

 
    fclose(fp);

    system("pause");
    return 0;
}

你这个应该用fread,fwrite读写结构体吧,写定义一个结构体,3个变量,然后读写结构体就可以了。

明天找我

请参考该代码进行改进:

/* Note:Your choice is C IDE */
#include "stdio.h"

struct SNAKE
{
    int direction;
    int life;
    int node;
    int level;
    int score;
}snake;
struct FOOD{
    int x;
    int y;
    int yes;    
}food;
void main()
{
  FILE *fp;
  snake.direction=1;
  snake.life=1;
  snake.node=3;
  snake.level=1;
  snake.score=0;
  
  food.x=100;
  food.y=200;
  food.yes=1;
  fp = fopen("d:\\snake.dat","wb+");
  if(fp==NULL){
      printf("can not open file.\n");
      exit(0);
  }
  fwrite(&snake,sizeof(struct SNAKE),1,fp);
  fwrite(&food,sizeof(struct FOOD),1,fp);
  fclose(fp);
}

您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632