Link to home
Start Free TrialLog in
Avatar of pote
pote

asked on

File open, Change, and save.

I want to update a .ini file via an executable. First I need to be able to read the .ini file, then change 1 line, then save the file to its original location. I can't just do a file replace because the .ini file may differ from machine to machine. I do however know that the line I need to change will always remain on line 9. How can i open the file, do a line replace then save the file?
Avatar of jkr
jkr
Flag of Germany image

Hmm - assuming you're on a Windows' platform, you might want to use 'WitePrivateProfileString()' to change the line instead of doing that manually, e.g.

WritePrivateProfileString ( "entry", "KeyToReplace", "New String", "c:\\windows\\yourfile.ini");
ASKER CERTIFIED SOLUTION
Avatar of KangaRoo
KangaRoo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of KangaRoo
KangaRoo

Hey, missed your comment jkr. Would be a lot easier indeed....
Hmm, KangaRoo, your approach would also require to copy the new file to the old location...
Yes, but that clutters too much.

char* temp = strdup(tmpnam(0));
char* inifile = "YourIniFile.ini";
rename(inifile, temp);
FILE* in = fopen(temp, "rt");
FILE* out = fopen(inifile, "wt");
replace(in, out, 9, "new text\n");
fclose(out);
fclose(in);
remove(temp);


Avatar of pote

ASKER

Thanks for the help, I have a good handle now.
Much appreciated.
Pote
Avatar of pote

ASKER

Thanks for the help, I have a good handle now.
Much appreciated.
Pote