C语言文件操作:使用临时文件修改图书信息
C语言文件操作:使用临时文件修改图书信息
在这段代码中,我们使用C语言实现了一个修改图书信息的功能。让我们深入探讨一下代码是如何工作的,以及为什么使用临时文件是一个好主意。cvoid modifyBook() { char bookCode[20]; printf('请输入要修改的图书编号:'); scanf('%s', bookCode);
FILE *file = fopen('book_storage.txt', 'r'); if (file == NULL) { printf('无法打开图书信息文件!
'); return; }
int found = 0; Book book; FILE *tempFile = fopen('temp.txt', 'w'); if (tempFile == NULL) { printf('无法创建临时文件!
'); fclose(file); return; }
while (fscanf(file, '%s', book.bookCode) != EOF) { fscanf(file, '%s', book.bookName); fscanf(file, '%s', book.author); fscanf(file, '%s', book.publisher); fscanf(file, '%s', book.bookkind); fscanf(file, '%s', book.bookkinds); fscanf(file, '%d', &book.quantity);
if (strcmp(book.bookCode, bookCode) == 0) { printf('请输入新的书名:'); scanf('%s', book.bookName); printf('请输入新的作者:'); scanf('%s', book.author); printf('请输入新的出版社:'); scanf('%s', book.publisher); printf('请输入新的图书种类:'); scanf('%s', book.bookkind); printf('请输入新的图书种类编号:'); scanf('%s', book.bookkinds); printf('请输入新的价格:'); scanf('%d', &book.quantity); found = 1; }
fprintf(tempFile, '%s
', book.bookCode); fprintf(tempFile, '%s ', book.bookName); fprintf(tempFile, '%s ', book.author); fprintf(tempFile, '%s ', book.publisher); fprintf(tempFile, '%s ', book.bookkind); fprintf(tempFile, '%s ', book.bookkinds); fprintf(tempFile, '%d ', book.quantity); }
fclose(file); fclose(tempFile);
if (!found) { printf('没有找到相关图书!
'); remove('temp.txt'); return; }
remove('book_storage.txt'); rename('temp.txt', 'book_storage.txt');
printf('修改成功!
');}
为什么要使用临时文件?
直接修改原始文件看似更直接,但存在风险。如果在修改过程中发生错误(例如程序崩溃或断电),原始文件的数据可能会损坏。使用临时文件可以避免这种情况:
- 数据安全: 我们首先将修改后的图书信息写入
temp.txt,而不是直接修改book_storage.txt。 2. 原子操作: 只有在所有修改都成功写入临时文件后,我们才会替换原始文件。这确保了如果出现问题,原始文件仍然保持完整。
时间复杂度分析
使用临时文件确实会带来一些额外的文件读写开销。但是,这种开销通常是可以接受的,特别是考虑到它带来的数据安全优势。
- 直接修改: 时间复杂度主要取决于查找目标图书信息的时间,通常是 O(n),其中 n 是图书数量。* 使用临时文件: 时间复杂度仍然是 O(n),因为我们需要读取和写入所有图书信息。
总结
尽管使用临时文件可能会略微增加时间复杂度,但在修改重要数据时,它提供了宝贵的数据安全性和完整性保障。
原文地址: https://www.cveoy.top/t/topic/fvQg 著作权归作者所有。请勿转载和采集!