473,699 Members | 2,702 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

read from file question

Hi ,

I have a question about a file operation i want to do . I have a data
file lets say X bytes . I want to read the file and delete a byte
every 2nd byte . I am a little comfused ,my approach is like this .

main()
{
char buf[1024];
FILE *fp;
fp=fopen("data" , "rb");

while(!feof(fp) ) {
fread(buf, 1, 1, fp);
}

fclose(fp);
}

ok ,with this i can read 1 byte at a time till end .Now what i want to
do is .... i want to have on buf the 1 byte ,3rd byte .. 5th .. etc
and discard 2nd .. 4th ...etc .My thought was to take the position of
the file pointer ,
example : position= ftell(fp) and if position % 2 == 0 then do not
read ..

but i dont know if i am on right way or is a correct way to do what i
want .I will appreciate comments on how to approach it . thanks in
advance .

Jul 2 '07 #1
10 2055
Arquitecto wrote:
Hi ,

I have a question about a file operation i want to do . I have a data
file lets say X bytes . I want to read the file and delete a byte
every 2nd byte . I am a little comfused ,my approach is like this .

main()
{
char buf[1024];
FILE *fp;
fp=fopen("data" , "rb");

while(!feof(fp) ) {
fread(buf, 1, 1, fp);
}

fclose(fp);
}

This doesn't do what you think; you repeatedly read
a single byte into the first element of buf[].

1. Prefer to check the return value of fread instead
of testing feof. fread may encounter errors before
getting to end of file.

2. To use fread to read one byte at a time you'll need
a pointer to the current position in the buffer.
ok ,with this i can read 1 byte at a time till end .Now what i want to
do is .... i want to have on buf the 1 byte ,3rd byte .. 5th .. etc
and discard 2nd .. 4th ...etc .My thought was to take the position of
the file pointer ,
example : position= ftell(fp) and if position % 2 == 0 then do not
read ..

but i dont know if i am on right way or is a correct way to do what i
want .I will appreciate comments on how to approach it . thanks in
advance .
So you can try to read the whole file at once and then copy
every other char to your result buffer, or read the file one
byte at a time and put only the odd indexed bytes into your
buffer (remembering that you need to keep track of the current
buffer position). There are a few ways you can do that, but
you can do it without using ftell.

--
imalone
Jul 2 '07 #2
"Arquitecto " wrote:
I have a question about a file operation i want to do . I have a data
file lets say X bytes . I want to read the file and delete a byte
every 2nd byte . I am a little comfused ,my approach is like this .

main()
{
char buf[1024];
FILE *fp;
fp=fopen("data" , "rb");

while(!feof(fp) ) {
fread(buf, 1, 1, fp);
}

fclose(fp);
}

ok ,with this i can read 1 byte at a time till end .Now what i want to
do is .... i want to have on buf the 1 byte ,3rd byte .. 5th .. etc
and discard 2nd .. 4th ...etc .My thought was to take the position of
the file pointer ,
example : position= ftell(fp) and if position % 2 == 0 then do not
read ..

but i dont know if i am on right way or is a correct way to do what i
want .I will appreciate comments on how to approach it . thanks in
advance .
I would do it like this. Create an output buffer and put the desired data
in it using the indexing operations. Then write the output buffer to a new
file. When you are done, delete the original file and rename the new file
to have the name of the old file.
Jul 2 '07 #3
"osmium" <r1********@com cast.netwrites:
"Arquitecto " wrote:
>I have a question about a file operation i want to do . I have a data
file lets say X bytes . I want to read the file and delete a byte
every 2nd byte .
[...]
I would do it like this. Create an output buffer and put the
desired data in it using the indexing operations. Then write the
output buffer to a new file. When you are done, delete the original
file and rename the new file to have the name of the old file.
That implies storing half the contents of the input file in memory,
without knowing how big the input file is. Allocating memory for this
can be tricky; realloc should do it *if* it's possible at all.

But it's not necessary. As you're reading the input file, write every
other character to the output file. When you're done, close the input
and output files and rename the output file. (And do error checking.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 2 '07 #4
"Keith Thompson" writes:
"osmium" <r1********@com cast.netwrites:
>"Arquitecto " wrote:
>>I have a question about a file operation i want to do . I have a data
file lets say X bytes . I want to read the file and delete a byte
every 2nd byte .
[...]
>I would do it like this. Create an output buffer and put the
desired data in it using the indexing operations. Then write the
output buffer to a new file. When you are done, delete the original
file and rename the new file to have the name of the old file.

That implies storing half the contents of the input file in memory,
without knowing how big the input file is. Allocating memory for this
can be tricky; realloc should do it *if* it's possible at all.
No, it implies a 1024K input buffer and a 512K output buffer, based on my
quick reading of what the OP was up to.

I'll do the implying and you do the inferring, that's the way it's usually
done.
Jul 2 '07 #5

"Arquitecto " <x3****@gmail.c omha scritto nel messaggio news:11******** **************@ w5g2000hsg.goog legroups.com...
Hi ,

I have a question about a file operation i want to do . I have a data
file lets say X bytes . I want to read the file and delete a byte
every 2nd byte . I am a little comfused ,my approach is like this .

main()
{
char buf[1024];
FILE *fp;
fp=fopen("data" , "rb");

while(!feof(fp) ) {
fread(buf, 1, 1, fp);
}

fclose(fp);
}

ok ,with this i can read 1 byte at a time till end .Now what i want to
do is .... i want to have on buf the 1 byte ,3rd byte .. 5th .. etc
and discard 2nd .. 4th ...etc .My thought was to take the position of
the file pointer ,
example : position= ftell(fp) and if position % 2 == 0 then do not
read ..

but i dont know if i am on right way or is a correct way to do what i
want .I will appreciate comments on how to approach it . thanks in
advance .
Try this: (not compiled, not tested)
#include <stdio.h>
#include <stdlib.h/* for EXIT_FAILURE */
int main(void)
{
char buf[1024];
int ch;
int i;
FILE *fp = fopen("data", "rb");
if (fp == NULL) {
perror("Read error");
return EXIT_FAILURE;
}
for (i = 0; i < sizeof buf; i++) {
ch = getc(fp);
if (ch == EOF)
break;
else
buf[i] = ch;
(void)getc(fp); /*discard odd bytes*/
}
fclose(fp);
return 0;
}
Jul 2 '07 #6
Nice Army, worked :) i also allocated buf memory dynamically with
calloc and now works nice xD ,thanks everyone :)
Army1987 :
"Arquitecto " <x3****@gmail.c omha scritto nel messaggio news:11******** **************@ w5g2000hsg.goog legroups.com...
Hi ,

I have a question about a file operation i want to do . I have a data
file lets say X bytes . I want to read the file and delete a byte
every 2nd byte . I am a little comfused ,my approach is like this .

main()
{
char buf[1024];
FILE *fp;
fp=fopen("data" , "rb");

while(!feof(fp) ) {
fread(buf, 1, 1, fp);
}

fclose(fp);
}

ok ,with this i can read 1 byte at a time till end .Now what i want to
do is .... i want to have on buf the 1 byte ,3rd byte .. 5th .. etc
and discard 2nd .. 4th ...etc .My thought was to take the position of
the file pointer ,
example : position= ftell(fp) and if position % 2 == 0 then do not
read ..

but i dont know if i am on right way or is a correct way to do what i
want .I will appreciate comments on how to approach it . thanks in
advance .

Try this: (not compiled, not tested)
#include <stdio.h>
#include <stdlib.h/* for EXIT_FAILURE */
int main(void)
{
char buf[1024];
int ch;
int i;
FILE *fp = fopen("data", "rb");
if (fp == NULL) {
perror("Read error");
return EXIT_FAILURE;
}
for (i = 0; i < sizeof buf; i++) {
ch = getc(fp);
if (ch == EOF)
break;
else
buf[i] = ch;
(void)getc(fp); /*discard odd bytes*/
}
fclose(fp);
return 0;
}
Jul 2 '07 #7
"osmium" <r1********@com cast.netwrites:
"Keith Thompson" writes:
>"osmium" <r1********@com cast.netwrites:
>>"Arquitecto " wrote:
I have a question about a file operation i want to do . I have a data
file lets say X bytes . I want to read the file and delete a byte
every 2nd byte .
[...]
>>I would do it like this. Create an output buffer and put the
desired data in it using the indexing operations. Then write the
output buffer to a new file. When you are done, delete the original
file and rename the new file to have the name of the old file.

That implies storing half the contents of the input file in memory,
without knowing how big the input file is. Allocating memory for this
can be tricky; realloc should do it *if* it's possible at all.

No, it implies a 1024K input buffer and a 512K output buffer, based on my
quick reading of what the OP was up to.
I'll accept that that's what you meant, but it's not what you wrote.
You didn't mention a specific buffer size (isn't a 1-megabyte input
buffer bigger than it needs to be?), nor did you mention or imply a
loop.

If I were doing this, I'd just use fgetc() and fputc(), writing every
other input character to the output file, and let the stdio
implementation take care of any buffering. That also has the
advantage of not needing special-case code if the file size isn't a
multiple of the input buffer size (though that's not a huge deal).
I'll do the implying and you do the inferring, that's the way it's usually
done.
And that's exactly what I did.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 2 '07 #8
Arquitecto <x3****@gmail.c omwrote:
# Hi ,
#
# I have a question about a file operation i want to do . I have a data
# file lets say X bytes . I want to read the file and delete a byte
# every 2nd byte . I am a little comfused ,my approach is like this .

With careful use of fseek and fread, you can modify the file in
place, but it simpler to scan the file once, writing every other
byte to a temporary file or saved to an internal buffer (if you have
enough memory), and the copy back to the original file.

Also you may need some way to truncate the file to half its size.
fopen(...,"r"). ..fclose(...).. .fopen(...,"w") is one way to
truncate the file. Your system may have additional calls like
ftruncate.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
Who's leading this mob?
Jul 3 '07 #9
Arquitecto wrote: *** and top-posted - fixed ***
Army1987 wrote:
>"Arquitecto " <x3****@gmail.c omha scritto nel messaggio
>>I have a question about a file operation i want to do . I have a
data file lets say X bytes . I want to read the file and delete
a byte every 2nd byte . I am a little comfused ,my approach is
like this .
.... snip ...
>>
Try this: (not compiled, not tested)
#include <stdio.h>
#include <stdlib.h/* for EXIT_FAILURE */
int main(void)
{
char buf[1024];
int ch;
int i;
FILE *fp = fopen("data", "rb");
if (fp == NULL) {
perror("Read error");
return EXIT_FAILURE;
}
for (i = 0; i < sizeof buf; i++) {
ch = getc(fp);
if (ch == EOF)
break;
else
buf[i] = ch;
(void)getc(fp); /*discard odd bytes*/
}
fclose(fp);
return 0;
}

Nice Army, worked :) i also allocated buf memory dynamically with
calloc and now works nice xD ,thanks everyone :)
Please do not top-post. Your answer belongs after (or intermixed
with) the quoted material to which you reply, after snipping all
irrelevant material. I fixed this one. See the following links:

--
<http://www.catb.org/~esr/faqs/smart-questions.html>
<http://www.caliburn.nl/topposting.html >
<http://www.netmeister. org/news/learn2quote.htm l>
<http://cfaj.freeshell. org/google/ (taming google)
<http://members.fortune city.com/nnqweb/ (newusers)

--
Posted via a free Usenet account from http://www.teranews.com

Jul 3 '07 #10

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

Similar topics

3
7966
by: deko | last post by:
It's nice to be able to generate an html table from a PHP array. I know how to do this, but the array in question is built from a file. The file in question can be very long, and I only want the first 10 lines. So, I'd like to reduce the overhead it takes to read the file into the array by limiting the number of lines read in - rather than have the entire file read in and then limiting the output to the html table. $visits=...
7
2256
by: Naren | last post by:
Hello All, Can any one help me in this file read problem. #include <stdio.h> int main() {
5
2027
by: Arvind P Rangan | last post by:
Hi, i like to read an existing xml file which has a schema defined to it, and then write or add data to the existing xml file using vb.net/c#. May be this Question has been answered earlier. Pls if anyone knows the link or example let me know Thanks ARvind.
2
2122
by: sani8888 | last post by:
Hi everybody I am a beginner with C++ programming. And I need some help. How can I start with this program *********** The program is using a text file of information as the source of the questions. The program starts by outputting a simple text information screen: Question Master
14
5229
by: Frank | last post by:
I see that ImageFormat includes exif. But I can't find out if I've System.Drawing.Image.FromStream or something like it can read and/or write that format.
7
3040
by: bowlderster | last post by:
Hello, all. This is the text file named test.txt. 1041 1467 7334 9500 2169 7724 3478 3358 9962 7464 6705 2145 6281 8827 1961 1491 3995 3942 5827 6436 6391 6604 4902 1153 1292 4382 9421 1716 2718 2895 I wanna to read the data to an array, as the follows:
6
2488
by: portCo | last post by:
Hello there, I am creating a vb application which is some like like a questionare. Application read a text file which contains many questions and display one question and the input is needed from user to calculate the score. Here is a problem. I can read a text file. However, it's read whole file at a time. So,
2
5449
by: Kevin Ar18 | last post by:
I posted this on the forum, but nobody seems to know the solution: http://python-forum.org/py/viewtopic.php?t=5230 I have a zip file that is several GB in size, and one of the files inside of it is several GB in size. When it comes time to read the 5+GB file from inside the zip file, it fails with the following error: File "...\zipfile.py", line 491, in read bytes = self.fp.read(zinfo.compress_size) OverflowError: long it too large to...
6
3215
by: =?Utf-8?B?VGFtbXkgTmVqYWRpYW4=?= | last post by:
Hi, can someone please let me know how I can read xml elements using object oriented program. I created a class to use the get and set properties however I dont know how I can pass the values from xml file to the class and use the values in my form. Thanks -- Nejadian
0
9172
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8908
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8880
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7745
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6532
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5869
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3054
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2344
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.