Amit Kulkarni wrote:
Hi,
I have small problem.
I want to truncate a line in a text file using C file handling
functions and write new line in place of it. How do I do it?
e.g.
"example.txt"
Line 1: This is a text file.
Line 2: Second line of it.
Now I want to truncate first line and replace it with suppose
following text: "This is first line"
How do I do it using C file handling functions like fputs, fscanf,
fseek.
FAQ Question 19.14
How can I insert or delete a line (or record) in the middle of a file?
located at:
http://www.eskimo.com/~scs/C-faq/q19.14.html
seems to be related to your question.
The faq says that you probably can't, short of rewriting the file.
To rewrite the file, I believe the best approach is as you read the
input file, example.txt, copy it to a temp file, replacing the
line to delete with the replacement line. Then rename the temp file
to example.txt.
Function replaceline defined below is an untested example:
#include <stdio.h>
int replaceline(const char *fname, unsigned linenr,
const char *replacetxt);
int main(void)
{
if(replaceline("example.txt",1,"This is the first line"))
puts("The file was successfully modified");
else puts("The file was not sucessfully modified");
return 0;
}
int replaceline(const char *fname,unsigned linenr,
const char *replacetxt)
{
FILE *fpi,*fpo;
int ch;
unsigned count;
if(!fname || !linenr || !replacetxt) return 0;
if((fpi = fopen(fname,"r")) == NULL)
{
perror("Error opening file for reading");
return 0;
}
if((fpo = fopen("temp.txt","w")) == NULL)
{
perror("Error opening file time.txt");
fclose(fpi);
return 0;
}
for(count = 1; (ch = fgetc(fpi)) != EOF; )
{
if(count == linenr)
{
while((ch = fgetc(fpi)) != EOF && ch != '\n') ;
if(0 > fprintf(fpo,"%s\n",replacetxt))
{
fclose(fpi);
fclose(fpo);
return 0;
}
count++;
if(ch == EOF) break;
}
else if(EOF == fputc(ch,fpo))
{
fclose(fpi);
fclose(fpo);
return 0;
}
if(ch == '\n') count++;
}
fclose(fpo);
if(ferror(fpi))
{
fclose(fpi);
return 0;
}
fclose(fpi);
if(count == 1 || count <= linenr) return 0;
remove(fname);
rename("temp.txt",fname);
return 1;
}
--
Al Bowers
Tampa, Fl USA
mailto:
xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/