473,799 Members | 3,093 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

knowing exact string array length ?

Hi. Im newbie in C language. I have a binary file with many character
arrays of 50 character defined as

char array[50]

But in some cases, many of these 50 characters are not being used. I
would like to know how could I know how many characters are really being
used in each array ?

Thanks
Alberto
Jun 17 '06
26 2588
alberto schrieb:
Michael Mair escribió:
alberto schrieb:
Keith Thompson escribió:
alberto <a@a.com> writes:

> Hi. Im newbie in C language. I have a binary file with many character
> arrays of 50 character defined as
>
> char array[50]
>
> But in some cases, many of these 50 characters are not being used. I
> would like to know how could I know how many characters are really
> being used in each array ?

If you can define what you mean by "used", the answer will be obvious.
If you can't, there is no answer.

I told on previous massage.
For example, I declare this array:

char arr[50];

And I want to put on that variable what user write on the keyboard
with scanf function (for example, his name). But some times the user
will type 20 characters, and other times will type 40 characters...

The same if the array would be on a file. But how do I know exactly
how many characters typed the user ?


You restricted yourself to a binary file, thus you do not know
how many characters are "used" -- you read 50 and then determine
how many are "used".
If you change your notion to "the file contains zero-terminated
character sequences (vulgo: strings) each of which is no longer
than 50 characters including the terminator", you can read up
to 50 characters, stop earlier when you encounter '\0' and know
how many characters you read ("used") up to that point.
This is curiously close to "the text file contains lines of up
to 50 characters including the newline character". C provides
a function to deal with this case: fgets(). You can use fgets()
also to read from stdin. If you want to be on the safe side,
you can check whether the user really entered/the file really
contained such a character sequence: The last character of the
string's "content" must be a '\n'.
Especially for reading from stdin, you often are restricted to
line-buffered input, so you get the user's input only after
the user hit return.
strlen() can be used to determine the number of characters plus
the '\n'.
If you do not need the '\n', you can overwrite it with '\0'.


tnx for info. Yes, the array of chars is a member of a struct and stored
in a binery file. I think I should read each "register" of the file, and
then try to determine the real lenght of the field "array of char" and
after that call calloc or malloc function properly. Correct ?


This depends. As this is a newsgroup about C, use code to convey
what you are talking about -- this makes clear what you are
trying to do.
If I understood you correctly, you have a binary file which
contains a number of data "registers" which you read in as
struct:
struct myFooRegister {
....
char bar[50];
....
};
Now, you want to "repackage" the data to another internal format,
say
struct myBaz {
....
char *qux;
....
};
You could have gone with "char qux[50];" as well but have
reason to believe that the additional effort of allocating and
freeing memory is well spent as you really need the memory[*].
Now, you want to have
struct myBaz baz;
char *baz_qux = malloc(strlen(f oo_reg.bar) + 1);
if (baz_qux != NULL) {
strcpy(baz_qux, foo_reg.bar);
}
else {
/* Your error handling here */
}
baz.qux = baz_qux;
Is this what you mean?

Cheers
Michael
[*] For fifty bytes, it usually is not worth it. Say you have
25 bytes "used" on average. You get at least an additional
sizeof (char*) bytes for the pointer itself, some memory for
the system's internal allocation data, and maybe the system
gives you always 64 bytes, 256 bytes, or 1K to make sure that
there is no "odd-sized hole" in the memory and that you can
realloc() without having to copy the contents.
You _can_ of course write some memory handling of your own
to take care of that but it probably is not worth the overhead.

However, it certainly is a good exercise :-)
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Jun 17 '06 #11
alberto wrote:
Hi. Im newbie in C language. I have a binary file with many character
arrays of 50 character defined as

char array[50]

But in some cases, many of these 50 characters are not being used. I
would like to know how could I know how many characters are really being
used in each array ?

Thanks
Alberto


Assuming a binary file consisting of 'char array[50]' elements, and
assuming further that the data in the elements are strings, you can
fseek the file on 50-byte boundaries, fread 50 bytes into a memory array
and then run strlen() on the array.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Jun 17 '06 #12
alberto wrote:
Hi. Im newbie in C language. I have a binary file with many character
arrays of 50 character defined as

char array[50]

But in some cases, many of these 50 characters are not being used. I
would like to know how could I know how many characters are really being
used in each array ?

Thanks
Alberto


I presume you are wanting to know how many bytes were read from the
file. If this is the case then you can simply store the return value of
fread. This will tell you how many bytes it actually read.
Jun 17 '06 #13
Richard Heathfield <in*****@invali d.invalid> writes:
Malcolm said:

<snip>
struct record
{
char *astring;
};

Will store a string of any length, if you allocate the "astring" member
with malloc().


Nonsense, Malcolm. Care to try again?


It makes sense if you assume that "allocate a pointer" is shorthand
for "allocate an array and set the pointer to point to its first
element". (But I'm not sure I see the point of wrapping it in a
structure.)

--
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.
Jun 17 '06 #14
Keith Thompson said:
Richard Heathfield <in*****@invali d.invalid> writes:
Malcolm said:

<snip>
struct record
{
char *astring;
};

Will store a string of any length, if you allocate the "astring" member
with malloc().
Nonsense, Malcolm. Care to try again?


It makes sense if you assume that "allocate a pointer" is shorthand
for "allocate an array and set the pointer to point to its first
element".


It still won't store a string of *any* length, though. There are infinitely
many strings. Of these, infinitely many are infinitely long, and Malcolm
could reasonably argue that he didn't mean those, but if we discount them,
there remain infinitely many strings that are finite in length but still so
very very long that they are unrepresentable within a single universe, let
alone a single machine.
(But I'm not sure I see the point of wrapping it in a
structure.)


That, at least, makes sense as a first cut which is heading in a direction
such as this:

struct elastistring
{
char *astring;
size_t curlen;
size_t maxlen;
};

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 17 '06 #15
On Sat, 17 Jun 2006 12:39:15 -0500, Joe Estock
<je*****@NOSPAN nutextonline.co m> wrote:
alberto wrote:
Hi. Im newbie in C language. I have a binary file with many character
arrays of 50 character defined as

char array[50]

But in some cases, many of these 50 characters are not being used. I
would like to know how could I know how many characters are really being
used in each array ?

Thanks
Alberto


I presume you are wanting to know how many bytes were read from the
file. If this is the case then you can simply store the return value of
fread. This will tell you how many bytes it actually read.


fread is not a string oriented function. In the absence of an I/O
error or an end of data condition, it will always read the requested
number of bytes, regardless of how many are '\0'. Additionally,
unless fread is called with the second argument set to 1, the return
value is the number of objects read, not the number of bytes.
Remove del for email
Jun 18 '06 #16
On Sat, 17 Jun 2006 10:50:53 +0200, alberto <a@a.com> wrote:
Bill Pursell escribió:
alberto wrote:
Hi. Im newbie in C language. I have a binary file with many character
arrays of 50 character defined as

char array[50]

But in some cases, many of these 50 characters are not being used. I
would like to know how could I know how many characters are really being
used in each array ?

What do you mean by "used"? Do you mean that they are non-zero?
The following will give you a count of how many of the first characters
are non-zero.

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

#define BLOCK_SIZE 50
int
main(void)
{
char buf[BLOCK_SIZE+1];
int count=0;

buf[BLOCK_SIZE] = 0;
while(fread(buf , sizeof *buf, BLOCK_SIZE, stdin) == BLOCK_SIZE)
printf("Block %d used %d bytes\n", ++count,
strlen(buf));
}

tnbx for your answer. Yes, I mean that if I have the array

char buf[50]

then some times it will contain 20 characters not '\0' I want to know
the amount of these characters, because I want to do a linked dynamic
list with pointers and each node should have the "string" of the static
array of 50 chars with really characters not '\0', so I must know the
number and after that use calloc or malloc functions


Binary files often contain '\0' bytes in positions other than the end
of strings. Is the data in your binary file truly strings or is it
possible that there could be imbedded '\0' bytes and more data in buf
that follows? If they are strings, why are you processing the file in
binary mode?
Remove del for email
Jun 18 '06 #17
Barry Schwarz <sc******@doezl .net> writes:
[...]
Binary files often contain '\0' bytes in positions other than the end
of strings. Is the data in your binary file truly strings or is it
possible that there could be imbedded '\0' bytes and more data in buf
that follows? If they are strings, why are you processing the file in
binary mode?


Strings are arrays of char terminated by '\0'. A '\0' character
normally wouldn't appear in a text file. (Text files contain lines,
which are often read into strings.)

--
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.
Jun 18 '06 #18

"Richard Heathfield" <in*****@invali d.invalid> wrote

It makes sense if you assume that "allocate a pointer" is shorthand
for "allocate an array and set the pointer to point to its first
element".


It still won't store a string of *any* length, though. There are
infinitely
many strings. Of these, infinitely many are infinitely long, and Malcolm
could reasonably argue that he didn't mean those, but if we discount them,
there remain infinitely many strings that are finite in length but still
so
very very long that they are unrepresentable within a single universe, let
alone a single machine.

A infinite string isn't a string, because C stirngs are NUL-terminated and
an infinite array has no terminating member.
I do take the point about long strings. If a size_t won't hold the length of
my string (the Encyclopedia Britannica, not a contrived example in any way)
the what is the point of it?

I recommend for C2006 a arbitrary-precison representation of size_t.
--
Buy my book 12 Common Atheist Arguments (refuted)
$1.25 download or $7.20 paper, available www.lulu.com/bgy1mm

Jun 18 '06 #19
Barry Schwarz escribió:
On Sat, 17 Jun 2006 12:39:15 -0500, Joe Estock
<je*****@NOSPAN nutextonline.co m> wrote:
alberto wrote:
Hi. Im newbie in C language. I have a binary file with many character
arrays of 50 character defined as

char array[50]

But in some cases, many of these 50 characters are not being used. I
would like to know how could I know how many characters are really being
used in each array ?

Thanks
Alberto

I presume you are wanting to know how many bytes were read from the
file. If this is the case then you can simply store the return value of
fread. This will tell you how many bytes it actually read.


fread is not a string oriented function. In the absence of an I/O
error or an end of data condition, it will always read the requested
number of bytes, regardless of how many are '\0'. Additionally,
unless fread is called with the second argument set to 1, the return
value is the number of objects read, not the number of bytes.
Remove del for email

the file is a binary file containing some "structs" , and one field of
the struct is

char array[50]

which I must "cut" when I find the first '\0' character to know the real
characters used.

So I think fread can be used here
Jun 18 '06 #20

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

Similar topics

21
23178
by: Andreas Lobinger | last post by:
Aloha, i wanted to ask another problem, but as i started to build an example... How to generate (memory and time)-efficient a string containing random characters? I have never worked with generators, so my solution at the moment is: import string import random random.seed(14)
3
2325
by: matthurne | last post by:
I'm doing a chapter 12 exercise from Accelerated C++ ... writing a string-like class which stores its data in a low-level way. My class, called Str, uses a char array and length variable. I've gotten everything working that I want working so far, except for std::istream& operator>>(std::istream&, Str&) The way my Str class manages itself of course requires that the size of the char array to store is known when it is allocated. The...
7
7606
by: Eric | last post by:
Hi All, I need to XOR two same-length Strings against each other. I'm assuming that, in order to do so, I'll need to convert each String to a BitArray. Thus, my question is this: is there an easy way to convert a String to a BitArray (and back again)? I explained the ultimate goal (XORing two Strings) so that, if anyone has a better idea of how to go about this they may (hopefully) bring that up...?
2
2195
by: Digital Fart | last post by:
following code would split a string "a != b" into 2 strings "a" and "b". but is there a way to know what seperator was used? string charSeparators = { "=", ">=", "<=" , "!=" }; string s1 = "field != value" result = s1.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
4
9700
by: mflll | last post by:
I am looking into the different techniques of handling arrays of edit boxes in Java Script. The first program below works fine. However, are there better ways of doing this, where the person writing the JavaScript doesn't have to pass the index in the "onChange" event name. I thought that one might be able to use "this.value" or compare this as
4
2813
by: Jason | last post by:
I need to open a file for reading, but I only know part of it's name. The file I want to read is in the format of xxx-yyyy-zzz.EXT The last three digits of the file name are different on each pc, for example PC7 has xxx-yyyy-zz1.ext PC5 has xxx-yyyy-zz2.ext PC3 has xxx-yyyy-zz8.ext
12
3231
by: Pascal | last post by:
hello and soory for my english here is the query :"how to split a string in a random way" I try my first shot in vb 2005 express and would like to split a number in several pieces in a random way without success. for example if the number is 123 456 : i would like to have some random strings like theese : (12 * 10 000) + (345 * 10) + (6*1) or (123*1 000)+(4*100)+(5*10)+(6*1) etc...
10
18638
by: Lonifasiko | last post by:
Hi, Just want to replace character at index 1 of a string with another character. Just want to replace character at that position. I thought Replace method would be overloaded with an index parameter with which you can write wanted character at that position. But no, Replace method only allows replacing one known character with another. The problem is I don't know the character to replace, just must replace the character at a known...
14
1734
by: Stevo | last post by:
If you split a string into an array using the split method, it's not working the way I'd expect it to. That doesn't mean it's wrong of course, but would anyone else agree it's working somewhat illogically? Here's a test I just put together that splits on "&". The test strings are: "a&b" = (Correct!) I expect array length 2 and I get 2 "a&" = (Incorrect!) I expect array length 1 but I get 2 "a" = (Correct!) I expect array length 1 and...
0
9538
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
10249
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...
1
10219
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
10025
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
9068
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
5461
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...
0
5584
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4138
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
3
2937
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.