我创建了一个更新文件值然后重命名的函数。
我的代码:
void UpdateBooks()
{
system("CLS");
char *update[5] = {malloc(30),malloc(30),malloc(30),malloc(30),malloc(30)};
int coop = 0;
struct Books book;
char oldfn[] = "d:/booksdata.txt";
char newfn[] = "d:/booksdata_temp.txt";
int deletecheck = 0;
char *myisbnumber = malloc(4);
char line[256];
char * pch;
int countcheck = 0;
allocatebooks(&book);
fp = fopen(oldfn,"r");
fpa = fopen(newfn,"w+");
if (fp == NULL || fpa == NULL)
{
printf("Error opening file!\n");
exit(1);
}
printf("Enter ISBN Number Of The Book You Want To Update:\n");
scanf("%10s",myisbnumber);
while (fgets(line,sizeof line,fp) != NULL)
{
pch = strtok (line,",");
while (pch != NULL)
{
if(countcheck == 0)
book.name = pch;
else if(countcheck == 1)
book.author = pch;
else if(countcheck == 2)
book.bookserialnumber = pch;
else if(countcheck == 3)
book.isbnnumber = pch;
else if(countcheck == 4)
book.edition = pch;
else if(countcheck == 5)
book.is_reserved = pch;
pch = strtok (NULL, ",");
countcheck++;
}
if(strcmp(myisbnumber,book.isbnnumber) != 0)
{
fprintf(fpa,"%s,%s,%s,%s,%s,%s,\n",book.name,book.author,book.bookserialnumber,book.isbnnumber,book.edition,book.is_reserved);
}
else
{
deletecheck++;
RedoUpdate:
system("CLS");
coop = 0;
printf("What do you want to Update:\n");
printf("1.Name\t %s\n2.Author\t %s\n3.Serial Number\t %s\n4.Edition\t %s\n5.Is_Reserved\t %s\n6.Nothing to Update\n",book.name,book.author,book.bookserialnumber,book.edition,book.is_reserved);
scanf("%d",&coop);
if(coop > 0 && coop <= 5)
{
printf("Enter New Value\n");
scanf("%s",update[coop]);
if(coop == 1)
book.name = update[coop];
else if(coop == 2)
book.author = update[coop];
else if(coop == 3)
book.bookserialnumber = update[coop];
else if(coop == 4)
book.edition = update[coop];
else if(coop == 5)
book.is_reserved = update[coop];
goto RedoUpdate;
}
fprintf(fpa,"%s,%s,%s,%s,%s,%s,\n",book.name,book.author,book.bookserialnumber,book.isbnnumber,book.edition,book.is_reserved);
printf("Updated!\n");
}
countcheck = 0;
}
if(deletecheck == 0)
goto END;
if(fclose(fp) != 0)
perror("File Not Closed FP\n");
if(fclose(fpa) != 0)
perror("File Not Closed FPA\n");
if(remove(oldfn) == -1)
{
perror("Remove Error");
exit(1);
}
if(rename(newfn,oldfn) == -1)
{
perror("Rename Error");
exit(1);
}
printf("Completed!\n");
END:
getch();
}
整个代码正常工作。我也使用fclose关闭文件,但是当我尝试重命名它时,出现“权限被拒绝”错误。
当使用rename(newfn,oldfn)时,我得到:权限被拒绝错误
最佳答案
从ISO / IEC9899:
7.19.4.2重命名功能
概要
1 #include <stdio.h>
int rename(const char *old, const char *new);
从原型可以看到:您在错误的位置使用了新旧参数。
关于c - 重命名功能在C中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27253015/