Re: Copying fread behaviour on char array



Giox wrote:

Hello everybody I want to create a routine that mimic the fread
behavior operating on char array.
I wrote

size_t fread_char(void* buf, size_t sz, size_t n, char* string_source)
{

memcpy(buf, string_source, sz*n);
string_source += n*sz;

return n;
}

When I leave the routine the string_source doesn't change its value, it
seems that the operation string_source += n*sz; has not been performed

C passes parameters by value, so fread_char()'s "string_source" variable
contains the _value_ of the parameter passed to it. (Basically, in this
case, it's a copy of the pointer.)

When fread_char() modifies string_source, it modifies its own local copy,
not the caller's original variable.

One way to handle this is to pass the address of the char*, rather than
the char* itself:

size_t fread_char(void* buf, size_t sz, size_t n, char** string_source)
{
memcpy(buf, *string_source, sz*n);
*string_source += n*sz;
return n;
}

Another method would be to define a struct to correspond to the FILE
struct used by fread()/etc. and pass a pointer to the struct rather
than the buffer itself. (The struct would contain, at a minimum, the
same thing as "string_source" above. However, you might want to have
both an "original" string pointer and a "current" pointer, plus a
"length", should you want to be able to simulate fseek and the like.)


--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:ThisIsASpamTrap@xxxxxxxxx>

.



Relevant Pages

  • Re: Hidden SSIDs
    ... When an AP has a hidden SSID, ieee80211 fails, at least with wpa_supplicant, ... The existing routine, ... struct iw_request_info *info, ... char *start, char *stop, ...
    (Linux-Kernel)
  • [PATCH]a tar filesystem for 2.6.10-rc1-mm3
    ... +static int tarfs_readdir(struct file * filp, ... struct tarent *dir_tarent, *ent; ... +static int tarfs_readlink(struct dentry *dentry, char *buffer, int buflen) ...
    (Linux-Kernel)
  • [PATCH] a tar filesystem for 2.6.*(easily access tar file)
    ... +static int tarfs_readdir(struct file * filp, ... struct tarent *dir_tarent, *ent; ... +static int tarfs_readlink(struct dentry *dentry, char *buffer, int buflen) ...
    (Linux-Kernel)
  • [PATCH]a tar filesystem for 2.6.10-rc1-mm3
    ... +static int tarfs_readdir(struct file * filp, ... struct tarent *dir_tarent, *ent; ... +static int tarfs_readlink(struct dentry *dentry, char *buffer, int buflen) ...
    (Linux-Kernel)
  • [PATCH 6/14] score - New architecure port to SunplusCT S+CORE
    ... +struct sgttyb { ... char sg_ispeed; ... +static inline unsigned long get_PEVN ... * Checks if a pointer to a block of memory in user space is valid. ...
    (Linux-Kernel)