If I use this code alone (with a main function) it works.
But when I include this function in my project, it give two files :
annuaire_client.txt
and annuaire1.txt
The code used is provided below:
void delete_client(){
FILE *annuaire_client,*annuaire1;
printf("\t\t\t\t\t\t\t\tNum de compte a supprimee: ");
int delete_line;
scanf("%d",&delete_line);
char ch;
int line = 1;
//ouvrir le fichier original
annuaire_client = fopen("annuaire_client.txt", "r");
ch = getc(annuaire_client);
//retour au debut
rewind(annuaire_client);
//ouvrir nouveau fichier
annuaire1 = fopen("annuaire1.txt", "w");
while (ch != EOF)
{
if (ch == '\n')
{
line++;
}
//sautez la line a supprimer
if (line != delete_line)
{
//copier les lines vers annuaire1.txt
fprintf(annuaire1,"%c",ch);
}
ch = getc(annuaire_client);
}
fclose(annuaire1);
fclose(annuaire_client);
remove("annuaire_client.txt");
rename("annuaire1.txt","annuaire_client.txt");
}
You should check the returned value of remove and rename:
if (remove("annuaire_client.txt") != 0) {
/* handle error */
}
if (rename("annuaire1.txt","annuaire_client.txt") == -1) {
/* handle error */
}
One of many possibilities is that you keep descriptor opened by main function while calling remove. Make sure you pair all fopen
with fclose
or even if you unlink
/ remove
paths your process will still keep (deleted) descriptors open which may cause fatal errors if you reach the limit of descriptors allocated for it ( fopen
will fail - this has happened to me today, so it is not purely artificial situation). Remember also, it is undefined behavior to call fclose
on invalid pointer, ie not a FILE*
, on NULL in particular.
You can try check the result code for your functions. For instance, for rename
function you can use some code like:
#include <errno.h>
(...)
int ret;
ret = rename("annuaire1.txt", "annuaire_client.txt");
if(ret == 0)
{
printf("File renamed successfully");
}
else
{
printf("Error: unable to rename the file");
fprintf(stderr, "System error (%d): %s\n", errno, strerror(errno);
}
Try writing the full path of the file in the remove function and in the new name in the rename function. For example:
remove("C:\\Documents\\annuaire_client.txt");
rename("anuuaire1.txt","C:\\Documents\\annuaire_client.txt");
Remember to use the \\\\ instead of \\
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.