醉晨. 2022-12-30 22:23 采纳率: 72.7%
浏览 25
已结题

在文件内存放一组数字,修改后输出

建文件 data.txt,文件内存放了一组数字,要实现以下功能:

1、读取该文件内的这组数字;

2、然后对其进行排序,要求按升序排序;

3、将排序后的内容另起一行输出到 data.txt 中。

【举例】

data.txt 中的原始数据为:

11.2 -98 33.6 52.1 0

程序运行后,data.txt 中的内容将被修改为:

11.2 -98 33.6 52.1 0

-98 0 11.2 33.6 52.1


#include <stdio.h>
#include <stdlib.h>
int main(){
    FILE*fp;
    char ch,data[10];
    printf("请输入所用的文件名:");
    scanf("%s",date);
    getchar();
     if((fp=fopen(data,"w"))=NULL)
    {printf("无法打开此文件\n");
        exit(0);
    }
    ch=getchar();
    while(ch!=\0){
        fputc(ch,fp);
    printf("\n");
    int j,k;
    for(int i = 0;i < 9;i++) {
    for(j = 0;j<10-i;j++) {
        if(data[j]<date[j-1])
        {
            k=date[j-1];
            date[j-1]=date[j];
            date[j]=k;
        }
    }
    }
    putchar(ch);
    ch=getchar();
    }
    fclose(fp);
    putchar(10);
    return 0;
}

我不知道该怎么做,文件这一节好懵。我的思路是先建一个date文件,然后在文件里输入一组数,然后排序输出
有没有人能教我一下该怎么改(>﹏<)

  • 写回答

1条回答 默认 最新

  • ShowMeAI 2022-12-30 22:50
    关注

    首先,要读取文件内的数字,我们需要使用 fscanf() 函数。然后我们可以使用冒泡排序算法对数字进行排序。最后,我们可以使用 fprintf() 函数将排序后的数字写回文件。

    下面是实现上述功能的代码示例:

    #include <stdio.h>
    
    #define MAX_SIZE 10  // 最多可以读入的数字个数
    
    int main() {
        // 打开文件
        FILE* fp = fopen("data.txt", "r+");
        if (fp == NULL) {
            printf("无法打开文件\n");
            return 0;
        }
    
        // 读取文件中的数字
        float numbers[MAX_SIZE];
        int numCount = 0;
        while (fscanf(fp, "%f", &numbers[numCount]) == 1) {
            numCount++;
        }
    
        // 对数字进行排序
        for (int i = 0; i < numCount; i++) {
            for (int j = 0; j < numCount - i - 1; j++) {
                if (numbers[j] > numbers[j + 1]) {
                    float temp = numbers[j];
                    numbers[j] = numbers[j + 1];
                    numbers[j + 1] = temp;
                }
            }
        }
    
        // 将排序后的数字写回文件
        fseek(fp, 0, SEEK_SET);  // 将文件指针移到文件开头
        for (int i = 0; i < numCount; i++) {
            fprintf(fp, "%.2f ", numbers[i]);
        }
        fprintf(fp, "\n");
    
        // 关闭文件
        fclose(fp);
    
        return 0;
    }
    
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 1月10日
  • 修改了问题 12月30日
  • 创建了问题 12月30日