473,657 Members | 2,419 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problem using fread, fwrite, and fsetpos

Hi,

I'm having a problem reading and writing to a file. What I'm trying
to do is read a file, modify the portion of the file that I just read,
and then write the modified data back to the same location in the
file.

What is happening, is I can read the file, either in entirety or only
part of it. And no matter what I try setting the position to, using
fsetpos, it always gets set back to the very beginning of the file. I
wrote sample code which demonstrates this.

#include <stdio.h>

int main()
{
FILE* input= fopen("test.dat ", "rb+");

int read = 0;
while(!feof(inp ut))
{
fread(&read, sizeof(int), 1, input);
}

fpos_t pos = 10; /* some random location in the file, 10 used as
example */
fsetpos(input, &pos);

int temp = 3;
fwrite(&temp, sizeof(int), 1, input);
fclose(input);
return 0;
}

When I call fsetpos(input, &pos), I am watching the values of the
FILE*, input. No matter what the value of pos is, the _ptr member of
input, gets set to the same value of _base.

I've read the posts saying you need to use an fsetpos, rewind, or
fseek, to change from read or write back into undetermined mode, and I
don't see why I'm having this problem.

Any help would be greatly appreciated. This problem has been plaguing
me for the last week.

Thanks,
Bryan
Nov 13 '05 #1
8 15351
Brady wrote:
I'm having a problem reading and writing to a file. What I'm trying
to do is read a file, modify the portion of the file that I just read,
and then write the modified data back to the same location in the
file.
[...]
fpos_t pos = 10; /* some random location in the file, 10 used as
example */


And here I get an error: "Invalid initializer". Unlike fseek(), fsetpos()
don't use long as the second parameter but a struct. Either You use fseek
(input, pos, SEEK_SET) (with pos as long, not fpos_t) or You write 10
characters, call fgetpos (input, &pos) and write the rest. Then You can use
pos with fsetpos().

--
Best Regards
Sven
Nov 13 '05 #2
ba*****@pitt.ed u (Brady) wrote:
#include <stdio.h>

int main()
{
FILE* input= fopen("test.dat ", "rb+");

int read = 0;
while(!feof(inp ut))
This is not the right way to read a file. Read the FAQ:
<http://www.eskimo.com/~scs/C-faq/q12.2.html>.
{
fread(&read, sizeof(int), 1, input);
}

fpos_t pos = 10; /* some random location in the file, 10 used as
example */
fsetpos(input, &pos);


From the latest public draft of the Standard:

[#2] The fsetpos function sets the mbstate_t object (if any)
and file position indicator for the stream pointed to by
stream according to the value of the object pointed to by
pos, which shall be a value obtained from an earlier
successful call to the fgetpos function on a stream
associated with the same file.

Note the last clause. You cannot just pass a random number to fsetpos().
In fact, fpos_t isn't even required to be any kind of scalar, so
assigning 10 to it is not legal. You need to get your position from
fgetpos() itself, otherwise fsetpos() isn't required to work.

Richard
Nov 13 '05 #3
Sven Gohlke <sv**@clio.in-berlin.de> wrote:
Brady wrote:
fpos_t pos = 10; /* some random location in the file, 10 used as
example */


And here I get an error: "Invalid initializer". Unlike fseek(), fsetpos()
don't use long as the second parameter but a struct.


Not necessarily. You cannot rely on it being a long _or_ a struct. It's
an fpos_t; and that's all you know it is.

Richard
Nov 13 '05 #4
Hi
The fsetpos function sets the file-position indicator for stream to
the value of pos, which is obtained in a prior call to fgetpos against
stream.
So you have to use fgetpos aprior to fsetpos.

see a sample code given below.
Regards
[Anaz K Kabeer]

* FGETPOS.C: This program opens a file and reads
* bytes at several different locations.
*/

#include <stdio.h>

void main( void )
{
FILE *stream;
fpos_t pos;
char buffer[20];

if( (stream = fopen( "fgetpos.c" , "rb" )) == NULL )
printf( "Trouble opening file\n" );
else
{
/* Read some data and then check the position. */
fread( buffer, sizeof( char ), 10, stream );
if( fgetpos( stream, &pos ) != 0 )
perror( "fgetpos error" );
else
{
fread( buffer, sizeof( char ), 10, stream );
printf( "10 bytes at byte %ld: %.10s\n", pos, buffer );
}

/* Set a new position and read more data */
pos = 140;
if( fsetpos( stream, &pos ) != 0 )
perror( "fsetpos error" );

fread( buffer, sizeof( char ), 10, stream );
printf( "10 bytes at byte %ld: %.10s\n", pos, buffer );
fclose( stream );
}
}
Nov 13 '05 #5


Brady wrote:
Hi,

I'm having a problem reading and writing to a file. What I'm trying
to do is read a file, modify the portion of the file that I just read,
and then write the modified data back to the same location in the
file.

What is happening, is I can read the file, either in entirety or only
part of it. And no matter what I try setting the position to, using
fsetpos, it always gets set back to the very beginning of the file. I
wrote sample code which demonstrates this.

#include <stdio.h>

int main()
{
FILE* input= fopen("test.dat ", "rb+");

int read = 0;
while(!feof(inp ut))
{
fread(&read, sizeof(int), 1, input);
}

fpos_t pos = 10; /* some random location in the file, 10 used as
example */
fsetpos(input, &pos);

int temp = 3;
fwrite(&temp, sizeof(int), 1, input);
fclose(input);
return 0;
}

When I call fsetpos(input, &pos), I am watching the values of the
FILE*, input. No matter what the value of pos is, the _ptr member of
input, gets set to the same value of _base.

I've read the posts saying you need to use an fsetpos, rewind, or
fseek, to change from read or write back into undetermined mode, and I
don't see why I'm having this problem.

Any help would be greatly appreciated. This problem has been plaguing
me for the last week.


How do you know that the file was opened or that any of the positioning
attemps were successful. You need to check the return values of these
functions.

/* test.c
change in file element 3 in an int array from 3 to 99 */

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
FILE* input= fopen("tes.dat" , "w+b");
int array[10] = {0,1,2,3,4,5,6, 7,8,9};
fpos_t pos,offset;
int temp = 99;

if(input == NULL)
{
perror("Unable to open the file");
exit(EXIT_FAILU RE);
}
printf("Before changing file: array[3] = %d\n",array[3]);
if(1 != fwrite(array,si zeof array,1,input))
{
perror("Unable to write to file test.dat");
exit(EXIT_FAILU RE);
}
rewind(input);
if(1 != fread(array,siz eof(int),1,inpu t))
{
perror("Unable to read to file test.dat");
exit(EXIT_FAILU RE);
}
if(0 != fgetpos(input,& offset))
{
perror("Error with fgetpos function");
exit(EXIT_FAILU RE);
}
printf("offset = %lu\n",offset);
pos = offset*3; /* positions at array[3] */
if(0 != fsetpos(input,& pos))
{
perror("Error with fsetpos function");
exit(EXIT_FAILU RE);
}
/* modify element 3 in the file.*/
if(1 != fwrite(&temp,si zeof temp, 1, input))
{
perror("Error writing to the file");
exit(EXIT_FAILU RE);
}
rewind(input);
if(1 != fread(array,siz eof array,1,input))
{
perror("Read error reading array");
exit(EXIT_FAILU RE);
}
printf("After changing file: array[3] = %d\n",array[3]);
fclose(input);
return 0;
}
--
Al Bowers
Tampa, Fl USA
mailto: xa*@abowers.com base.com (remove the x)
http://www.geocities.com/abowers822/

Nov 13 '05 #6
ba*****@pitt.ed u (Brady) wrote in message news:<3f******* *************** ****@posting.go ogle.com>...
Hi,

I'm having a problem reading and writing to a file. What I'm trying
to do is read a file, modify the portion of the file that I just read,
and then write the modified data back to the same location in the
file.

What is happening, is I can read the file, either in entirety or only
part of it. And no matter what I try setting the position to, using
fsetpos, it always gets set back to the very beginning of the file. I
wrote sample code which demonstrates this.

#include <stdio.h>

int main()
{
FILE* input= fopen("test.dat ", "rb+");

int read = 0;
you forget to check that you opened the file successfully.
while(!feof(inp ut))
{
fread(&read, sizeof(int), 1, input);
}

fpos_t pos = 10; /* some random location in the file, 10 used as
example */
unless you are using a c99 compiler, you cant mix variable
declarations and code.

also, according to the documentation on my system, fpos_t *may*
not be an int, as you assigned it.
fsetpos(input, &pos);
(from my man pages)

#include <stdio.h>
int fsetpos(FILE *FP, const fpos_t *POS);
(...)
You can use `fsetpos' to return the file identified by
FP to a previous position `*POS' (after first recording it
with `fgetpos').
(and from the same page)
ANSI C requires `fsetpos', but does not specify the nature
of `*POS' beyond identifying it as written by `fgetpos'.

this means that the second argument to fsetpos() *must* be of type
fpos_t, which can *only* be returned by fgetpos().

What you should do is use fgetpos() to store a value into the fpos_t
variable.

replace
pos = 10;

with
fseek (input, 10, SEEK_SET);
fgetpos (input, &pos);

also dont forget to check the return values of the functions. they
may be trying to tell you that (for example) you are setting an invalid
position in the file.

int temp = 3;
fwrite(&temp, sizeof(int), 1, input);
fclose(input);
return 0;
}

When I call fsetpos(input, &pos), I am watching the values of the
FILE*, input. No matter what the value of pos is, the _ptr member of ^^^^
there isn't any need to do this, just check the return values, and
remember that fpos_t may not be an integer.
input, gets set to the same value of _base.

I've read the posts saying you need to use an fsetpos, rewind, or
fseek, to change from read or write back into undetermined mode, and I


I have no idea what you are trying to say here. what is "undetermin ed
mode" ?

hth
goose,
Nov 13 '05 #7
In <3f************ ***@news.nl.net > rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
Sven Gohlke <sv**@clio.in-berlin.de> wrote:
Brady wrote:
> fpos_t pos = 10; /* some random location in the file, 10 used as
> example */


And here I get an error: "Invalid initializer". Unlike fseek(), fsetpos()
don't use long as the second parameter but a struct.


Not necessarily. You cannot rely on it being a long _or_ a struct. It's
an fpos_t; and that's all you know it is.


You also know what it cannot be: an array.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #8
On 16 Jul 2003 22:37:51 -0700, ba*****@pitt.ed u (Brady) wrote:
I'm having a problem reading and writing to a file. <snip>
What is happening, is I can read the file, either in entirety or only
part of it. And no matter what I try setting the position to, using
fsetpos, it always gets set back to the very beginning of the file. I
wrote sample code which demonstrates this. <snip>
When I call fsetpos(input, &pos), I am watching the values of the
FILE*, input. No matter what the value of pos is, the _ptr member of
input, gets set to the same value of _base.

In addition to the correct comments elsethread that fpos_t need not be
an integer type nor linear bytes even if it is and about feof(), even
if your call to fsetpos() actually worked, or if you used instead
fseek(pos,SEEK_ SET) which would work on a binary stream,
there is no reason to expect that the file position appears in the
FILE structure, whose contents are implemention-defined; on many,
perhaps most, operating systems it is handled entirely in the OS.

_ptr and _base on your implementation almost certainly refer to the
currently used/valid portion of the in-memory buffer, and after any
positioning call that buffer normally should be reset.
- David.Thompson1 at worldnet.att.ne t
Nov 13 '05 #9

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

Similar topics

2
9218
by: Kent Lewandowski | last post by:
hi all, Recently I wrote some stored procedures using java jdbc code (admittedly my first stab) and then tried to implement the same within java packages (for code reuse). I encountered problems doing this. I wanted to implemented a generic "Helper" class like this: /** * Helper
3
3499
by: syntax | last post by:
hi, i want to read a file using fread() in equal chunks through a for loop so that at the last call i dont get error..which way, i should read it? let me give an example, suppose i have 100 chars, i can read it in 50 chars for twice or 10 chars in ten times or 25 chars for 4 times...like this. Here, file size, i.e 100 chars is known to me....but if the file size is unknown then how can i read in equal chunks so that at the last call i...
22
1857
by: Rajshekhar | last post by:
Hi , i am writing a simple prgm to read a .txt file then store the contents into the array... program as follows: -------------------------- #include<stdio.h> int main() { FILE *fp1;
2
2581
by: mazsx | last post by:
Is there a portable way to use binary files? By portability I mean: Machine A (a supercomputer) with some compiler, my job runs there and outputs several megabytes of data. To save space and for better seekability, I use a binary format. Machine B (my desktop) with some other compiler analizes this data. So far I assumed that both architectures have the standard representation of the float, double and int types. I would like to use now...
3
11998
by: georges the man | last post by:
how do i read from a text file using fread
3
1955
by: Franky | last post by:
Been having a problem using a treeview. Work great the first time the form containing it is entered but not the second time. Took a while to create a small sample that exhibits the problem, but here it is. Seems to have something to do with doing ShowDialog Easy to reproduce this project, simply add two forms.
14
3698
by: Maria Mela | last post by:
Hello everyone... I´ve a problem with my code, when i put this lines: recsize = sizeof(p1); fseek(fp,-recsize,SEEK_CUR); fwrite(&p1,sizeof(p1),1,fp); getch(); The file was saved with correct values and with some windows informations too!?
4
3228
by: mickey22 | last post by:
Hi all, I have read a data file which is actually a 3d matrix 100 X 100 X 80 into a buffer say "data" using fread function.When it reads how is data actually stored?Is it stored contigously and how to access them. I am just using fread and no other manipulations in the function.Thanks in advance.
30
14267
by: empriser | last post by:
How to use fread/fwrite copy a file. When reach file's end, fread return 0, I don't konw how many bytes in buf.
0
8826
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...
0
8732
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8605
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
7330
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...
0
5632
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();...
0
4155
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2726
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
1955
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1615
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.