c语言:图书信息包括:书名、出版社、价格,从book.txt文件中读取5条图书信息,将其按照价格从低到高排序后,输出全部图书信息至bookpaixu.txt中,并在屏幕显示
时间: 2023-11-22 16:52:02 浏览: 123
代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BOOKS 5
#define MAX_NAME_LEN 50
#define MAX_PUBLISHER_LEN 50
struct book {
char name[MAX_NAME_LEN];
char publisher[MAX_PUBLISHER_LEN];
float price;
};
void sort_books(struct book books[], int n) {
int i, j;
struct book tmp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (books[i].price > books[j].price) {
tmp = books[i];
books[i] = books[j];
books[j] = tmp;
}
}
}
}
int main() {
struct book books[MAX_BOOKS];
FILE *fp_read, *fp_write;
int i;
fp_read = fopen("book.txt", "r");
if (fp_read == NULL) {
printf("Failed to open file book.txt\n");
return 1;
}
for (i = 0; i < MAX_BOOKS; i++) {
if (fscanf(fp_read, "%s%s%f", books[i].name, books[i].publisher, &books[i].price) != 3) {
printf("Failed to read book info\n");
fclose(fp_read);
return 1;
}
}
fclose(fp_read);
sort_books(books, MAX_BOOKS);
fp_write = fopen("bookpaixu.txt", "w");
if (fp_write == NULL) {
printf("Failed to open file bookpaixu.txt\n");
return 1;
}
for (i = 0; i < MAX_BOOKS; i++) {
printf("%s %s %f\n", books[i].name, books[i].publisher, books[i].price);
fprintf(fp_write, "%s %s %f\n", books[i].name, books[i].publisher, books[i].price);
}
fclose(fp_write);
return 0;
}
```
我们首先定义了一个结构体 `book` ,包含了书名、出版社和价格三个字段,然后定义了一个 `sort_books` 函数,用于对图书按照价格从低到高排序。
在 `main` 函数中,我们先从文件 `book.txt` 中读取五条图书信息,然后调用 `sort_books` 函数进行排序,最后将排序后的结果输出到屏幕和文件 `bookpaixu.txt` 中。
需要注意的是,我们在读取文件时使用了 `fscanf` 函数,该函数的返回值是成功读取的字段数,如果不等于 3,则表示读取失败。因此在读取过程中需要进行错误处理。
阅读全文