473,626 Members | 3,221 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

fseek on a file opened with _popen

Hello

Recently I discovered some problem. I have some C code
which determines how many bytes are available in a
file. Later I use this information to malloc a buffer of
the correct size before I read the bytes.
Determining the number of bytes available in a
file is done in 5 steps:

1. Use tell(aFile) to get the current position.
2. Use fseek(aFile, 0, SEEK_END) to move to the end.
3. Get the current position with tell(aFile) (this is the
size of the file in bytes).
4. I move to the position which I got in step 1 with fseek().
5. Subtract the current position from the file size to
get the number of bytes available.

This code is certainly not the most elegant solution but
it is portable. The code works for normal files under
windows and linux. The portability is also the reason
why I use tell() and fseek() instead of windows specific
code.

When I open a file with _popen I get a different result:
- Under linux the tell() of step 1 returns -1 which means
the file is not seekable. I can recognice this situation
and react accordingly (I cannot malloc the buffer beforehand.
Instead I malloc a smaller buffer which is realloced until
all bytes are read).
- Under windows the tell() of step 1 returns 0 which
means the file is seekable and is currently at position 0.
The other calls of fseek() and ftell() succeed also and
indicate that the number of available bytes is 0.
Therefore my program thinks that there are no bytes
available in the file opened with _popen.

The information that it is a file opened with _popen is
not available at that place in my program.

Now my question:
Is it possible to find out that a file (available in a
variable of type FILE * ) was opened with _popen?

Something like: Turn the FILE * into a handle and ask a
function about the file type. It is no problem for me to
insert windows specific code under an #ifdef

Thanks in advance Thomas Mertes

Seed7 Homepage: http://seed7.sourceforge.net
Seed7 - The extensible programming language: User defined statements
and operators, abstract data types, templates without special
syntax, OO with interfaces and multiple dispatch, statically typed,
interpreted or compiled, portable, runs under linux/unix/windows.
Feb 28 '08 #1
13 4482
th***********@g mx.at wrote:
Hello

Recently I discovered some problem. I have some C code
which determines how many bytes are available in a
file.
[snip]
The code works for normal files under
windows and linux.
[snip]
When I open a file with _popen I get a different result:
- Under linux the tell() of step 1 returns -1 which means
the file is not seekable. I can recognice this situation
and react accordingly (I cannot malloc the buffer beforehand.
Instead I malloc a smaller buffer which is realloced until
all bytes are read).
I hope you don't grow it a byte at a time :-)
- Under windows the tell() of step 1 returns 0 which
means the file is seekable and is currently at position 0.
The other calls of fseek() and ftell() succeed also and
indicate that the number of available bytes is 0.
Therefore my program thinks that there are no bytes
available in the file opened with _popen.
The information that it is a file opened with _popen is
not available at that place in my program.
Could you consider making it available, by providing a wrapper
mechanism? (That would probably be my favoured approach, rather
than looking for platform specifics...)
Now my question:
Is it possible to find out that a file (available in a
variable of type FILE * ) was opened with _popen?
As _popen is not part of the C standard, it's not really
something we would consider here. You'd probably do better
asking in a Windows newsgroup.
Feb 28 '08 #2
th***********@g mx.at wrote:
Hello

Recently I discovered some problem. I have some C code
which determines how many bytes are available in a
file. Later I use this information to malloc a buffer of
the correct size before I read the bytes.
Determining the number of bytes available in a
file is done in 5 steps:

1. Use tell(aFile) to get the current position.
Don't you man ftell() rather than tell()?
If not you're most üprobably lost here as that won't be a standard function.
2. Use fseek(aFile, 0, SEEK_END) to move to the end.
3. Get the current position with tell(aFile) (this is the
size of the file in bytes).
4. I move to the position which I got in step 1 with fseek().
5. Subtract the current position from the file size to
get the number of bytes available.

This code is certainly not the most elegant solution but
it is portable. The code works for normal files under
windows and linux. The portability is also the reason
why I use tell() and fseek() instead of windows specific
code.

When I open a file with _popen I get a different result:
no function _popen() in standard C (I think). In POSIX there's popen() (i.e.
without the leading underscore)
- Under linux the tell() of step 1 returns -1 which means
the file is not seekable. I can recognice this situation
and react accordingly (I cannot malloc the buffer beforehand.
Instead I malloc a smaller buffer which is realloced until
all bytes are read).
- Under windows the tell() of step 1 returns 0 which
means the file is seekable and is currently at position 0.
The other calls of fseek() and ftell() succeed also and
indicate that the number of available bytes is 0.
Therefore my program thinks that there are no bytes
available in the file opened with _popen.

The information that it is a file opened with _popen is
not available at that place in my program.

Now my question:
Is it possible to find out that a file (available in a
variable of type FILE * ) was opened with _popen?

Something like: Turn the FILE * into a handle and ask a
function about the file type. It is no problem for me to
insert windows specific code under an #ifdef
OT here (I think) but "int filno(FILE *stream);" might be what you're
looking for

Bye, Jojo
Feb 28 '08 #3
In article <fq**********@a ioe.org>,
Mark Bluemel <ma**********@p obox.comwrote:
> (I cannot malloc the buffer beforehand.
Instead I malloc a smaller buffer which is realloced until
all bytes are read).
>I hope you don't grow it a byte at a time :-)
That's not much of a problem with most malloc() implementations .

-- Richard
--
:wq
Feb 28 '08 #4
In article <0a************ *************** *******@z17g200 0hsg.googlegrou ps.com>,
<th***********@ gmx.atwrote:
>- Under linux the tell() of step 1 returns -1 which means
the file is not seekable. I can recognice this situation
and react accordingly (I cannot malloc the buffer beforehand.
Instead I malloc a smaller buffer which is realloced until
all bytes are read).
Why not use this strategy always?

As an optimisation, you could use the ftell() strategy to determine
the initial size to malloc().

-- Richard
--
:wq
Feb 28 '08 #5
On 28 Feb., 13:44, Mark Bluemel <mark_blue...@p obox.comwrote:
thomas.mer...@g mx.at wrote:
Hello
Recently I discovered some problem. I have some C code
which determines how many bytes are available in a
file.

[snip]
The code works for normal files under
windows and linux.

[snip]
When I open a file with _popen I get a different result:
- Under linux the tell() of step 1 returns -1 which means
the file is not seekable. I can recognice this situation
and react accordingly (I cannot malloc the buffer beforehand.
Instead I malloc a smaller buffer which is realloced until
all bytes are read).

I hope you don't grow it a byte at a time :-)
Actually I grow it in steps of 4096.
- Under windows the tell() of step 1 returns 0 which
means the file is seekable and is currently at position 0.
The other calls of fseek() and ftell() succeed also and
indicate that the number of available bytes is 0.
Therefore my program thinks that there are no bytes
available in the file opened with _popen.
The information that it is a file opened with _popen is
not available at that place in my program.

Could you consider making it available, by providing a wrapper
mechanism? (That would probably be my favoured approach, rather
than looking for platform specifics...)
A simplified version of the function using this functionality
is (please don't start nitpicking):

-----------------------------------------------
#include "stdlib.h"
#include "stdio.h"

#define READ_BLOCK_SIZE 4096
#define SIZ_STRI(len) ((sizeof(struct stristruct) - \
sizeof(unsigned char)) + (len) * sizeof(unsigned char))

typedef struct stristruct {
unsigned long int size;
unsigned char mem[1];
} *stritype;

stritype filGets (FILE *aFile, long length)

{
long current_file_po sition;
unsigned long int bytes_requested ;
unsigned long int bytes_there;
unsigned long int read_size_reque sted;
unsigned long int block_size_read ;
unsigned long int allocated_size;
unsigned long int result_size;
unsigned char *memory;
stritype resized_result;
stritype result;

/* filGets */
if (length < 0) {
result = NULL;
} else {
bytes_requested = (unsigned long int) length;
allocated_size = bytes_requested ;
result = (stritype) malloc(SIZ_STRI (allocated_size ));
if (result == NULL) {
/* Determine how many bytes are available in aFile */
if ((current_file_ position = ftell(aFile)) != -1) {
fseek(aFile, 0, SEEK_END);
bytes_there = (ftell(aFile) - current_file_po sition);
fseek(aFile, current_file_po sition, SEEK_SET);
/* Now we know that bytes_there bytes are available
in aFile */
if (bytes_there < bytes_requested ) {
allocated_size = bytes_there;
result = (stritype) malloc(SIZ_STRI (allocated_size ));
if (result == NULL) {
return(NULL);
} /* if */
} else {
return(NULL);
} /* if */
} /* if */
} /* if */
if (result != NULL) {
/* We have allocated at least as many bytes as
are available in the file */
result_size = (unsigned long int) fread(result->mem, 1,
(size_t) allocated_size, aFile);
} else {
/* We do not know how many bytes are avaliable therefore we
read blocks of READ_BLOCK_SIZE until we reach EOF */
allocated_size = READ_BLOCK_SIZE ;
result = (stritype) malloc(SIZ_STRI (allocated_size ));
if (result == NULL) {
return(NULL);
} else {
read_size_reque sted = READ_BLOCK_SIZE ;
if (read_size_requ ested bytes_requested ) {
read_size_reque sted = bytes_requested ;
} /* if */
block_size_read = fread(result->mem, 1,
read_size_reque sted, aFile);
result_size = block_size_read ;
while (block_size_rea d == READ_BLOCK_SIZE &&
result_size < bytes_requested ) {
allocated_size = result_size + READ_BLOCK_SIZE ;
resized_result = (stritype)
realloc(result, SIZ_STRI(alloca ted_size));
if (resized_result == NULL) {
free(result);
return(NULL);
} else {
result = resized_result;
memory = (unsigned char *) result->mem;
read_size_reque sted = READ_BLOCK_SIZE ;
if (result_size + read_size_reque sted >
bytes_requested ) {
read_size_reque sted = bytes_requested - result_size;
} /* if */
block_size_read = fread(&memory[result_size], 1,
read_size_reque sted, aFile);
result_size += block_size_read ;
} /* if */
} /* while */
} /* if */
} /* if */
result->size = result_size;
if (result_size < allocated_size) {
resized_result = (stritype)
realloc(result, SIZ_STRI(result _size));
if (resized_result == NULL) {
free(result);
return(NULL);
} else {
result = resized_result;
} /* if */
} /* if */
} /* if */
return(result);
} /* filGets */
-------------------------------------------

The function _popen() is not a standard function, but popen()
is. Btw.: Under windows I use MinGW and there the function
is also popen(). The problem stays open:

if you open a file with popen() (MinGW probably also cygwin)
under windows and you do a ftell() or fseek() you just
succeed as if it is an empty file. If you do the same in
linux the ftell() and fseek() functions return -1 which
indicate that the file is not seekable.

If someone has an idea: Please help.

Greetings Thomas Mertes

Seed7 Homepage: http://seed7.sourceforge.net
Seed7 - The extensible programming language: User defined statements
and operators, abstract data types, templates without special
syntax, OO with interfaces and multiple dispatch, statically typed,
interpreted or compiled, portable, runs under linux/unix/windows.
Feb 28 '08 #6
On 28 Feb., 14:19, rich...@cogsci. ed.ac.uk (Richard Tobin) wrote:
In article <0a41826a-30d2-4e47-b1ed-be13144bf...@z1 7g2000hsg.googl egroups.com>,

<thomas.mer...@ gmx.atwrote:
- Under linux the tell() of step 1 returns -1 which means
the file is not seekable. I can recognice this situation
and react accordingly (I cannot malloc the buffer beforehand.
Instead I malloc a smaller buffer which is realloced until
all bytes are read).

Why not use this strategy always?

As an optimisation, you could use the ftell() strategy to determine
the initial size to malloc().
This is just what I want. But for a pipe created with popen this
strategy is not possible: You cannot know how big a pipe can
grow. Therefore ftell() and fseek() return -1 for pipes.
Under windows it does not work for files (pipes) opened with
_popen() since ftell() and fseek() return 0 instead of -1.
Therefore I look for a possibility to recognize this situation.

Greetings Thomas Mertes

Seed7 Homepage: http://seed7.sourceforge.net
Seed7 - The extensible programming language: User defined statements
and operators, abstract data types, templates without special
syntax, OO with interfaces and multiple dispatch, statically typed,
interpreted or compiled, portable, runs under linux/unix/windows.
Feb 28 '08 #7
On 28 Feb., 13:48, "Joachim Schmitz" <nospam.j...@sc hmitz-digital.de>
wrote:
thomas.mer...@g mx.at wrote:
Hello
Recently I discovered some problem. I have some C code
which determines how many bytes are available in a
file. Later I use this information to malloc a buffer of
the correct size before I read the bytes.
Determining the number of bytes available in a
file is done in 5 steps:
1. Use tell(aFile) to get the current position.

Don't you man ftell() rather than tell()?
Yes you are right: I mean ftell()
If not you're most üprobably lost here as that won't be a standard function.
2. Use fseek(aFile, 0, SEEK_END) to move to the end.
3. Get the current position with tell(aFile) (this is the
size of the file in bytes).
4. I move to the position which I got in step 1 with fseek().
5. Subtract the current position from the file size to
get the number of bytes available.
This code is certainly not the most elegant solution but
it is portable. The code works for normal files under
windows and linux. The portability is also the reason
why I use tell() and fseek() instead of windows specific
code.
When I open a file with _popen I get a different result:

no function _popen() in standard C (I think). In POSIX there's popen() (i.e.
without the leading underscore)
I looked at the popen() more closely and I use popen()
under linux (gcc) and under windows (MinGW). the only place
using _popen() would be under windows (MSVC). But the actual
problem occours under windows(MinGW). So I can claim that
I actually use the POSIX popen().
- Under linux the tell() of step 1 returns -1 which means
the file is not seekable. I can recognice this situation
and react accordingly (I cannot malloc the buffer beforehand.
Instead I malloc a smaller buffer which is realloced until
all bytes are read).
- Under windows the tell() of step 1 returns 0 which
means the file is seekable and is currently at position 0.
The other calls of fseek() and ftell() succeed also and
indicate that the number of available bytes is 0.
Therefore my program thinks that there are no bytes
available in the file opened with _popen.
The information that it is a file opened with _popen is
not available at that place in my program.
Now my question:
Is it possible to find out that a file (available in a
variable of type FILE * ) was opened with _popen?
Something like: Turn the FILE * into a handle and ask a
function about the file type. It is no problem for me to
insert windows specific code under an #ifdef

OT here (I think) but "int filno(FILE *stream);" might be what you're
looking for
Does the fileno() function return a file handle under
windows?

May be I can use fstat and check for S_ISFIFO.
If that works MinGW has a bug.

Greetings Thomas Mertes

Seed7 Homepage: http://seed7.sourceforge.net
Seed7 - The extensible programming language: User defined statements
and operators, abstract data types, templates without special
syntax, OO with interfaces and multiple dispatch, statically typed,
interpreted or compiled, portable, runs under linux/unix/windows.
Feb 28 '08 #8
In article <cf************ *************** *******@34g2000 hsz.googlegroup s.com>,
<th***********@ gmx.atwrote:
>- Under linux the tell() of step 1 returns -1 which means
the file is not seekable. I can recognice this situation
and react accordingly (I cannot malloc the buffer beforehand.
Instead I malloc a smaller buffer which is realloced until
all bytes are read).
>Why not use this strategy always?
>As an optimisation, you could use the ftell() strategy to determine
the initial size to malloc().
>This is just what I want. But for a pipe created with popen this
strategy is not possible: You cannot know how big a pipe can
grow.
You misunderstand. *Don't* try to recognise the situation. *Always*
use the grow-the-buffer-as-you-read approach, so that you don't have
to know the size in advance.

But use the result of the ftell() strategy for the initial size.
It will be wrong if it happens to be a pipe, but it doesn't matter
that it's wrong - you'll just start with a buffer of zero bytes and
grow it to the right size as you read.

-- Richard
--
:wq
Feb 28 '08 #9
th***********@g mx.at wrote:
>...So I can claim that
I actually use the POSIX popen().
Which is a POSIX standard (see comp.unix.progr ammer) not a C standard.
Feb 28 '08 #10

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

Similar topics

1
3606
by: Michael | last post by:
Hello, Not sure if this is the right message board but I have an interesting problem. Using Visual Studio .NET, C++, I want to write an all-encompassing C++ program to download new files from an FTP Server. The C++ program will ftp to the server and download a list of files, match those files with the ones I've already received, put together a new ftp script and download.
62
6211
by: Christopher Benson-Manica | last post by:
On thinking about the "replace a word in a file" thread, I wondered how easy it would be to accomplish the same thing with only one file pointer. This led me to some questions... "For a text stream, offset must be zero, or a value returned by ftell (in which case origin must be SEEK_SET)." If offset is a value returned by ftell (which returns the current file position), and origin is SEEK_SET, then fseek() sets the position to the...
15
16049
by: TJ Walls | last post by:
Hello All, I am baffled ... I am trying to improve the speed of a program that I have written that performs random access within a file. It relies heavily on fseek and is very slow. To test, I wrote the following test program which just writes the numbers 1-167721 sequentially to a binary file: #include <stdio.h> #include <stdlib.h>
20
15160
by: Xenos | last post by:
Can anyone tell me what the standard says about using fseek (on a binary file) to seek past the end-of-file? I can't find anything in my (draft) copy of the standard, nor in the FAQ. Thanks
2
5224
by: John | last post by:
I have a file open using fopen and am reaing using fread. Does this mean that the OS (linux) already buffers this file? What is the buffer size? Can I change it? Thanks, --j
2
3541
by: cedarson | last post by:
I am writing a program and have been instructeed to use the 'fseek', 'ftell', and 'stat' functions, however, after looking in the online manual for each of these, I am still unsure on how to use them. In my program, I am to write a code that opens a file, uses 'stat' to determine the file size, use 'fseek' to move the offset of the pointer, and finally use 'ftell' to obtain the file pointer index. Will someone please help? Again, thanks...
10
5945
by: Kenneth Brody | last post by:
I recently ran into an "issue" related to text files and ftell/fseek, and I'd like to know if it's a bug, or simply an annoying, but still conforming, implementation. The platform is Windows, where text files use CF+LF (0x0d, 0x0a) to mark end-of-line. The file in question, however, was in Unix format, with only LF (0x0a) at the end of each line. First, does the above situation already invoke "implementation defined" or "undefined"...
14
3697
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!?
20
7519
by: ericunfuk | last post by:
If fseek() always clears EOF, is there a way for me to fread() from an offset of a file and still be able to detect EOF?i.e. withouting using fseek(). I also need to seek to an offset in the file frequently(forwards and backwards) and do fread() from that offset. Or better still, could anyone let me know some good ways to achieve what I need to do as above?Can I get hold of the file and being able to read in without using fread()? Using...
0
8196
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8705
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
8364
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
7193
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
6125
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
5574
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
4092
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
1808
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1511
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.