-
Rename file problem
i am trying to fix a problem with renaming a file function using rename
it will open file called "Country.txt" then search in deletecode field for "N" then save it in a new file"Temporary file" then have to rename "Country file to Backup file".
i don't know what the problem is
could you help me to fix this problem
Thanks
Code:
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include <ctype.h>
#include"rename.h"
void backu();
struct Country
{
int position;
char country[3],name[16];
char intcode[4];
char deletecode[2];
};
void main()
//void DeleteCountry()
{
int ch,result;
char ch1;
int e,i,count;
bool check,test;
FILE *f;
struct Country c;
system("cls");
f=fopen("a:\\Country.txt","r+");//
i=0;
count=0;
while(fread(&c,sizeof(c),1,f)==1)
{
puts(c.deletecode);
ch=strcmp(c.deletecode,"N");
if (ch==0)
{
f=fopen("a:\\CountryTemporary.txt","a+");//
struct Country temp[i];
printf("I:%d\n",i);
strcpy(temp[i].country,c.country);
strcpy(temp[i].name,c.name);
strcpy(temp[i].intcode,c.intcode);
strcpy(temp[i].deletecode,c.deletecode);
temp[i].position=c.position;
//fwrite(&temp,sizeof(temp),1,f);
//fclose(f);
puts(temp[i].country);
puts(temp[i].name);
i++;
}
count++;
}
/* Attempt to rename file: */
result = rename( "Country.txt", "CountryBackup.txt" );
if( result != 0 )
printf( "Could not rename " );
else
printf( "File renamed to " );
}
-
I thik it's not renaming the file because the file is still open...I'm not sure though
-
>void main ()
wrong, main returns an int, so use int main(void)
>f = fopen("a:\\Country.txt", "r+");
You should check that the open worked before using f.
If you are reading structs, you should use a binary mode.
>f = fopen("a:\\CountryTemporary.txt", "a+");
Why have you opened a new file with f, without first closing the original f?
>struct Country temp[i];
You can't declare variables in the middle of a function.
i is set to zero, so you aren't creating any array indexes anyway.
And no, you cannot rename a file that is in use.