473,382 Members | 1,814 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

HOW-TO Truncate first line in a file to zero length?

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.

Thnks in advance

------------------------------------------------------------------------------------------------------------------------------------------
Amit Kulkarni.
--------------------------------------------------------------------------------------------------------------------------------------------|
Everyone wishes to have truth on his side, but not everyone wishes to
be on the side of truth.
--------------------------------------------------------------------------------------------------------------------------------------------|
Nov 14 '05 #1
4 2900
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.

Thnks in advance

------------------------------------------------------------------------------------------------------------------------------------------
Amit Kulkarni.
--------------------------------------------------------------------------------------------------------------------------------------------|
Everyone wishes to have truth on his side, but not everyone wishes to
be on the side of truth.
--------------------------------------------------------------------------------------------------------------------------------------------|


It's not hard.

a) Read the whole file in to a bunch of character buffers that are
appropriately sized.
b) Change the first one.
c) Write all the buffers back out with something like fprintf or fputs.

Stream text files like this don't really support the ability to just
replace things in other ways because they aren't record-based. On some
OS's this was possible because even text files were treated like they
were records of (len, text), (len, text), etc.

But for the most part, Unix and other operating systems treat text files
as streams of bytes. So the only way to shorten or lengthen the stream
is to read all of the data in, replace just the part you want, and then
write out the whole thing all over again.

<OT non-ANSI C>
Now, if you want to do something that's a little simpler to code,
consider doing something like invoking sed on it and tell IT to
change line 1 to something that you want. That's an exercise I'll
leave to you :-)
</OT>

HTH
dbtid
Nov 14 '05 #2
dbtid <db***@dev.null.com> wrote:
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?
<snip>
a) Read the whole file in to a bunch of character buffers that are
appropriately sized.
b) Change the first one.
c) Write all the buffers back out with something like fprintf or fputs.


It's unnecessary and extremely wasteful WRT memory usage to buffer
the whole file contents. Writing the new first line to a temporary
file and streaming the remainder of the original file seems much more
appropriate, especially for huge files.

<snip>

Regards
--
Irrwahn Grausewitz (ir*******@freenet.de)
welcome to clc: http://www.ungerhu.com/jxh/clc.welcome.txt
clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
clc OT guide : http://benpfaff.org/writings/clc/off-topic.html
Nov 14 '05 #3


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/

Nov 14 '05 #4
Irrwahn Grausewitz wrote:
dbtid <db***@dev.null.com> wrote:
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?

<snip>
a) Read the whole file in to a bunch of character buffers that are
appropriately sized.
b) Change the first one.
c) Write all the buffers back out with something like fprintf or fputs.

It's unnecessary and extremely wasteful WRT memory usage to buffer
the whole file contents. Writing the new first line to a temporary
file and streaming the remainder of the original file seems much more
appropriate, especially for huge files.


I don't know why I wrote it that way. Of course you're correct.
It would be a whole lot simpler to just read up and spit out all
of the lines except for the one in question, one line at a time
into a single buffer.
<snip>

Regards

Nov 14 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Tom Szabo | last post by:
Just wandering how can you close a browser remotely. In some web applications the browser closes or refreshes periodically. How is that done and how can it be done through PHP? TIA, Tom
15
by: Reid Nichol | last post by:
Hello, I was wondering if I could control how many bytes are in an int and the byte order. In C/C++ I can use int32 but how do I do this in python? How can I control byte order?
0
by: v I n O | last post by:
hI Geeks Please do let me know how do i find how many instances sql server running on the single machine. or in the n/w my objective should with help of C#/vb.net
4
by: James Salisbury | last post by:
Hi, I was checking my parent's website salisbury.cabrera.net on google by entering villa rent spain cabrera I can see the required site, ranked at 4, but I am concerend by the return at 1 and 5...
2
by: Frances Del Rio | last post by:
http://www.emol.com/especiales/cocina_chilena/comida.asp this page is so neat (goes in pop-up..) how was this done? how do you give a layer (or div, I guess) a semi-transparency so you can still...
4
by: | last post by:
Developing, building, and testing. How do it the best? Learning from the world leader - Microsoft I'm very interested in how the developing/build/testing workflow @ Microsoft looks like. I...
4
by: Supra | last post by:
in vb6 listbox1.remove item 5 how will i do in vb.net? regards
7
by: anushhprabu | last post by:
#define q(k)main(){ return!puts(#k"\nPRABUq("#k")");} q(#define q(k)main(){return!puts(#k"\nq("#k")");}) guys i'm working on this code.. i got it fromnet.. how this is working.. anyone pls.....
0
by: candra | last post by:
Learn What Hackers Know? -General Hacking Information -Password Security -Scanning, Fingerprinting And Similar Techniques -How Hackers Attack Numerous Internet Services -How Hackers Attack Web...
2
by: belred | last post by:
i just read this blog about how many objects (types) are loaded for a hello world program in C#. http://blogs.msdn.com/abhinaba/archive/2008/09/15/how-many-types-are-loaded-for-hello-world.aspx ...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.