英文:
Looking for right fopen mode for my problem
问题
我创建了这个编程问题,其中我从二进制文件中读取书籍列表到结构体数组中。如果文件不存在,我希望程序创建该文件。
在这种情况下,我要求用户输入书籍和它们的作者。然后,我将这些信息写入文件作为一系列结构体。
如果文件已经存在,并且其中包含一些书籍(带有作者),我想要为用户提供选项,要么保留、删除或更新文件中的书籍条目。
如果用户删除了一些书籍,那么用户应该被给予选项来输入书籍的数量,只要未达到某个限制(最大书籍数量)为止。
我对使用fopen
来打开文件时应该使用哪种模式感到困惑。
-
如果使用
r+b
模式,如果文件不存在会导致错误。 -
如果使用
a+b
模式,写入只能追加。因此,如果用户决定删除一些书籍并输入其他书籍,这些信息将被顺序追加到文件中。
如何处理这个问题?
英文:
I have created this programming problem where I read list of books from a binary file into array of structs. If the file does not exist, then I want the program to create the file.
In this case, I ask the user to enter the books and their authors. Then I write this to the file as series of structs.
If the file already exists with some books (with authors) on it, I want to give an option to the user to either keep, delete or update the book entry of the file.
And if the user deletes some books, then user should be given option to enter number of books as long as some limit (MAX BOOKS) is not reached.
I am confused as to which mode should I use to open the file using fopen
.
-
If
r+b
mode is used, then there will be an error if the file doesn't exist. -
If
a+b
mode is used then writing can only be appended. So, if the user has decided to delete some books, and enter other books, this information will be be sequentially appended to the file.
How can this problem be approached ?
答案1
得分: 1
我使用不同模式的嵌套fopen
调用找到了解决这个问题的方法。如果pbooks
是指向名为book.dat
的二进制文件的FILE指针。那么我做了以下操作
FILE *pbooks;
if ((pbooks = fopen("book.dat", "r+b")) == NULL)
{
if ((pbooks = fopen("book.dat", "w+b")) == NULL)
{
exit(EXIT_FAILURE);
}
}
所以,最初,如果文件不存在,初始的fopen函数会返回NULL
,因此会执行内部的fopen语句并创建文件。当文件已经存在并且程序再次执行时,初始的fopen函数会成功执行,并且由于模式是r+b
,现有文件不会被截断,因此我们可以访问以前输入的数据。我已经测试过了,这个方法是有效的。如果这种方法在实际中被推荐使用,请留下评论。
英文:
I found a solution to this problem using nested fopen
calls in different modes.
If pbooks
is the FILE pointer to the binary file called book.dat
. Then I did the following
FILE * pbooks;
if ((pbooks = fopen("book.dat", "r+b")) == NULL)
{
if ((pbooks = fopen("book.dat", "w+b")) == NULL)
{
exit(EXIT_FAILURE);
}
}
So, initially, if the file doesn't exist, initial fopen function returns NULL
and so inner fopen statement is executed and the file is created. When the file is already created and the program is executed again, initial fopen function is executed successfully and since the mode is r+b
, the existing file is not truncated, so that we have access to the data which was entered earlier. I tested this and this is working. Please comment if this approach is recommended in practice.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论