实验7_文件应用编程

task1

源代码

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

#define N 80
#define M 100

typedef struct {
    char name[N];
    char author[N];
} Book;

void write();
void read();

int main() {
    printf("测试1: 把图书信息写入文本文件\n");
    write();

    printf("\n测试2: 从文本文件读取图书信息, 打印输出到屏幕\n");
    read();

    return 0;
}

void write() {
    Book x[] = { {"《雕塑家》", "斯科特.麦克劳德"},
                  {"《灯塔》", "克里斯多夫.夏布特"},
                  {"《人的局限性》", "塞缪尔.约翰生"},
                  {"《永不停步:玛格丽特.阿特伍德传》", "罗斯玛丽.沙利文"},
                  {"《大地之上》", "罗欣顿·米斯特里"},
                  {"《上学记》", "何兆武"},
                  {"《命运》", "蔡崇达"} };
    int n, i;
    FILE* fp;

    n = sizeof(x) / sizeof(x[0]);

    fp = fopen("data1.txt", "w");

    if (fp == NULL) {
        printf("fail to open file to write\n");
        return;
    }

    for (i = 0; i < n; ++i)
        fprintf(fp, "%-40s %-20s\n", x[i].name, x[i].author);

    fclose(fp);
}

void read() {
    Book x[M];
    int i, n;
    int number;

    FILE* fp;

    fp = fopen("data1.txt", "r");

    if (fp == NULL) {
        printf("fail to open file to read\n");
        return;
    }

    i = 0;
    while (!feof(fp)) {
        number = fscanf(fp, "%s%s", x[i].name, x[i].author);
        if (number != 2)
            break;
        i++;
    }
    n = i;

    for (i = 0; i < n; ++i)
        printf("%d. %-40s%-20s\n", i + 1, x[i].name, x[i].author);

    fclose(fp);
}

 

程序运行截图

task2

源代码

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

#define N 80
#define M 100

typedef struct {
    char name[N];      
    char author[N];     
} Book;

void write();
void read();

int main() {
    printf("测试1: 把图书信息以数据块方式写入二进制文件\n");
    write();

    printf("\n测试2: 从二进制文件读取图书信息, 打印输出到屏幕\n");
    read();

    return 0;
}

void write() {
    Book x[] = { {"《雕塑家》", "斯科特.麦克劳德"},
                  {"《灯塔》", "克里斯多夫.夏布特"},
                  {"《人的局限性》", "塞缪尔.约翰生"},
                  {"《永不停步:玛格丽特.阿特伍德传》", "罗斯玛丽.沙利文"},
                  {"《大地之上》", "罗欣顿·米斯特里"},
                  {"《上学记》", "何兆武"},
                  {"《命运》", "蔡崇达"} };
    int n;
    FILE* fp;

   
    n = sizeof(x) / sizeof(x[0]);

   
    fp = fopen("data2.dat", "wb");

    
    if (fp == NULL) {
        printf("fail to open file to write\n");
        return;
    }

   
    fwrite(x, sizeof(Book), n, fp);

    fclose(fp);
}

void read() {
    Book x[M];
    int i, n;
    int number;

    FILE* fp;

    
    fp = fopen("data2.dat", "rb");

    
    if (fp == NULL) {
        printf("fail to open file to read\n");
        return;
    }

    
    i = 0;
    while (!feof(fp)) {
        number = fread(&x[i], sizeof(Book), 1, fp);
        if (number != 1)
            break;
        i++;
    }

    
    n = i;
    for (i = 0; i < n; ++i)
        printf("%d. %-40s%-20s\n", i + 1, x[i].name, x[i].author);

    fclose(fp);
}

 

程序运行截图

task3

源代码

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define N 5
#define M 80

void write();
void read_str();
void read_char();

int main() {
    printf("测试1: 把一组字符信息以字符串方式写入文本文件\n");
    write();

    printf("\n测试2: 从文件以字符串方式读取, 输出到屏幕\n");
    read_str();

    printf("\n测试3: 从文件以单个字符方式读取, 输出到屏幕\n");
    read_char();

    return 0;
}

void write() {
    char* ptr[N] = { "Working\'s Blues",
                     "Everything Will Flow",
                     "Streets of London",
                     "Perfect Day",
                     "Philadelphia" };
    int i;
    FILE* fp;

    fp = fopen("data3.txt", "w");
    if (!fp) {
        printf("fail to open file to write\n");
        return;
    }

    for (i = 0; i < N; ++i) {
        fputs(ptr[i], fp);
        fputs("\n", fp);
    }

    fclose(fp);
}

void read_str() {
    char songs[N][M];
    int i;
    FILE* fp;

    fp = fopen("data3.txt", "r");
    if (!fp) {
        printf("fail to open file to read\n");
        return;
    }

    for (i = 0; i < N; ++i)
        fgets(songs[i], 80, fp);

    for (i = 0; i < N; ++i)
        printf("%d. %s", i + 1, songs[i]);

    fclose(fp);
}

void read_char() {
    char ch;
    FILE* fp;

    fp = fopen("data3.txt", "r");
    if (!fp) {
        printf("fail to open file to read\n");
        return;
    }

    while (!feof(fp)) {
        ch = fgetc(fp);
        if (ch == EOF)
            break;

        putchar(ch);
    }

    fclose(fp);
}

 

程序运行截图

 

task4

源代码

#define _CRT_SECURE_NO_WARNINGS

#include<stdio.h>
#include<ctype.h>

int main() {
    FILE* file;
    char filename[] = "data4.txt";
    int line_count = 0;
    int char_count = 0;
    char ch;

    file = fopen(filename, "rb");
    if (file == NULL) {
        printf("无法打开文件%s\n", filename);
        return 1;
    }
    while ((ch = fgetc(file)) != EOF) {
        if (ch == '\n') {
            line_count++;
        }
        else if (!isspace(ch)) {
            char_count++;
        }
    }
    if (char_count > 0 && line_count == 0) {
        line_count = 1;
    }
    else if (char_count > 0) {
        line_count++;
    }
    fclose(file);

    printf("data.text统计结果:\n");
    printf("行数:%d\n", line_count);
    printf("字符数(不计空白符):%d\n", char_count);

    return 0;
}

 

程序运行截图

 

task5

源代码

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

#define N 10

typedef struct {
    long id;            
    char name[20];      
    float objective;    
    float subjective;   
    float sum;          
    char result[10];    
} STU;


void read(STU st[], int n);
void write(STU st[], int n);
void output(STU st[], int n);
int process(STU st[], int n, STU st_pass[]);

int main() {
    STU stu[N], stu_pass[N];
    int cnt;
    double pass_rate;

    printf("从文件读入%d个考生信息...\n", N);
    read(stu, N);

    printf("\n对考生成绩进行统计...\n");
    cnt = process(stu, N, stu_pass);

    printf("\n通过考试的名单:\n");
    output(stu, N);   
    write(stu_pass, N);    

    pass_rate = 1.0 * cnt / N;
    printf("\n本次等级考试通过率: %.2f%%\n", pass_rate * 100);

    return 0;
}
void output(STU st[], int n) {
    int i;

    printf("准考证号\t姓名\t客观题得分\t操作题得分\n");
    for (i = 0; i < n; i++) {
        printf("%ld\t%s\t%.2f\t\t%.2f\t\n",
            st[i].id, st[i].name, st[i].objective,
            st[i].subjective, st[i].sum, st[i].result);
    }
}


void read(STU st[], int n) {
    int i;
    FILE* fin;

    fin = fopen("examinee.txt", "r");
    if (!fin) {
        printf("fail to open file\n");
        return;
    }

    for (i = 0; i < n; i++) {
        fscanf(fin, "%ld %s %f %f", &st[i].id, st[i].name,
            &st[i].objective, &st[i].subjective);
    }

    fclose(fin);
}


void write(STU st[], int n) {
    int i;
    FILE* fout;

    fout = fopen("list_pass.txt", "w");
    if (!fout) {
        printf("fail to open file\n");
        return;
    }

    fprintf(fout, "准考证号\t姓名\t客观题得分\t操作题得分\n");
    for (i = 0; i < n; i++) {
        fprintf(fout, "%ld\t%s\t%.2f\t\t%.2f\t\n",
            st[i].id, st[i].name, st[i].objective,
            st[i].subjective, st[i].sum, st[i].result);
    }

    fclose(fout);
}


int process(STU st[], int n, STU st_pass[]) {
    int i, pass_cnt = 0;

    for (i = 0; i < n; i++) {
        
        st[i].sum = st[i].objective + st[i].subjective;

        
        if (st[i].sum >= 60) {
            strcpy(st[i].result, "通过");
            st_pass[pass_cnt] = st[i]; 
            pass_cnt++;
        }
        else {
            strcpy(st[i].result, "未通过");
        }
    }

    return pass_cnt;
}

 

程序运行截图

 

task6

源代码

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define TOTAL_STUDENTS 80
#define WINNERS 5

typedef struct {
    char id[20];      
    char name[20];    
    char class[50];   
} Student;


void readStudents(Student students[], const char* filename);
void selectWinners(Student students[], Student winners[], int total, int winnerCount);
void displayWinners(Student winners[], int count);
void saveWinners(Student winners[], int count, const char* filename);
void sortWinners(Student winners[], int count);
void generateDateFilename(char* filename);

int main() {
    Student students[TOTAL_STUDENTS];
    Student winners[WINNERS];
    char filename[100];

    
    srand(time(NULL));

    
    readStudents(students, "list.txt");

    
    selectWinners(students, winners, TOTAL_STUDENTS, WINNERS);

    
    sortWinners(winners, WINNERS);

    
    printf("\n### 中奖名单\n");
    displayWinners(winners, WINNERS);

    
    generateDateFilename(filename);
    printf("\n### 保存到文件\n输入文件名: %s\n", filename);

    
    saveWinners(winners, WINNERS, filename);
    printf("保存成功!\n");

    return 0;
}


void readStudents(Student students[], const char* filename) {
    FILE* file = fopen(filename, "rb");
    if (file == NULL) {
        printf("无法打开文件 %s\n", filename);
        exit(1);
    }

    for (int i = 0; i < TOTAL_STUDENTS; i++) {
        fscanf(file, "%s %s %[^\n]", students[i].id, students[i].name, students[i].class);
    }

    fclose(file);
}


void selectWinners(Student students[], Student winners[], int total, int winnerCount) {
    int selected[TOTAL_STUDENTS] = { 0 }; 
    int count = 0;

    while (count < winnerCount) {
        int index = rand() % total;
        if (!selected[index]) {
            winners[count] = students[index];
            selected[index] = 1;
            count++;
        }
    }
}


void displayWinners(Student winners[], int count) {
    for (int i = 0; i < count; i++) {
        printf("%s\t%s\t%s\n", winners[i].id, winners[i].name, winners[i].class);
    }
}


void saveWinners(Student winners[], int count, const char* filename) {
    FILE* file = fopen(filename, "w");
    if (file == NULL) {
        printf("无法创建文件 %s\n", filename);
        exit(1);
    }

    fprintf(file, "### 中奖名单\n");
    for (int i = 0; i < count; i++) {
        fprintf(file, "%s\t%s\t%s\n", winners[i].id, winners[i].name, winners[i].class);
    }

    fclose(file);
}


void sortWinners(Student winners[], int count) {
    for (int i = 0; i < count - 1; i++) {
        for (int j = 0; j < count - i - 1; j++) {
            if (strcmp(winners[j].id, winners[j + 1].id) > 0) {
                Student temp = winners[j];
                winners[j] = winners[j + 1];
                winners[j + 1] = temp;
            }
        }
    }
}


void generateDateFilename(char* filename) {
    time_t now;
    struct tm* timeinfo;

    time(&now);
    timeinfo = localtime(&now);

    strftime(filename, 100, "%Y%m%d.txt", timeinfo);
}

 

程序运行截图

 

posted @ 2025-06-02 14:58  姚斯文  阅读(26)  评论(0)    收藏  举报