473,473 Members | 2,167 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Help With Strings

Hello friends at comp.lang.c,

I'm trying to combine 2 strings with a newline character at the end to write
to a file. When I view the file, the messages run together and some of the
str string is cut-off. A portion of the code is below. Any help would be
appreciated.

#define MAX_SIZE 256
char str[MAX_SIZE];
char lev[] = "INFO: ";
va_list ap;

va_start(ap, fmt);
vsprintf(str, fmt, ap);
va_end(ap);

strcat(lev, str);

write(fd, lev, strlen(fmt));
Nov 14 '05 #1
9 1652
"Craig" <NO****************@highstream.net> writes:
I'm trying to combine 2 strings with a newline character at the end to write
to a file. When I view the file, the messages run together and some of the
str string is cut-off. A portion of the code is below. Any help would be
appreciated.

#define MAX_SIZE 256
char str[MAX_SIZE];
char lev[] = "INFO: ";
va_list ap;

va_start(ap, fmt);
vsprintf(str, fmt, ap);
va_end(ap);

strcat(lev, str);

write(fd, lev, strlen(fmt));


The variable lev has a size of 7 bytes (6 for the characters of the
string literal used to initialize it, plus 1 for the trailing '\0').
You use strcat() to append more characters, but here's no room for
them. The result is undefined behavior, most likely overwriting some
other chunk of memory.

(You also risk writing past the end of str with your vsprintf() call,
unless you're positive that MAX_SIZE is big enough.)

Also, standard C has no write() function; fwrite() is standard and
more portable. That's not relevant to your problem, but it's
something you should be aware of.

I'm now going to go off on a tangent.

Speaking of that, I'm curious about something. ISO C defines the
fread() and fwrite() functions, and all the other stuff in <stdio.h>
that operates on FILE*'s. POSIX defines read() and write(), and all
the other stuff that operates on file descriptors (small integers).
Historically, I think that read() and write() are probably as old as,
or older than, fread() and fwrite(); ANSI chose to standardize the
latter, but not the former. Are there any real-world hosted
implementations that support fread() and fwrite() but *don't* also
support read() and write(), or is the historical precedent strong
enough to make read() and write() effectively universal?

I'm not at all suggesting that read()/write() should be part of
standard C, or that they should be considered topical here. I'm just
curious about their status.

--
Keith Thompson (The_Other_Keith) 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.
Nov 14 '05 #2
Keith Thompson wrote:
[...]
I'm now going to go off on a tangent.

Speaking of that, I'm curious about something. ISO C defines the
fread() and fwrite() functions, and all the other stuff in <stdio.h>
that operates on FILE*'s. POSIX defines read() and write(), and all
the other stuff that operates on file descriptors (small integers).
Historically, I think that read() and write() are probably as old as,
or older than, fread() and fwrite(); ANSI chose to standardize the
latter, but not the former. Are there any real-world hosted
implementations that support fread() and fwrite() but *don't* also
support read() and write(), or is the historical precedent strong
enough to make read() and write() effectively universal?


The Rationale discusses the C89 committee's thoughts on
the matter. The crux, it appears, is that read() et al. treat
a file as an array of characters, but this treatment is not
appropriate for all systems -- particularly for text files.
On a system where text lines are terminated with a CR/LF pair,
for example, what would be the semantics of lseek()ing to a
point just after the CR and then reading? Is the end-of-line
sequence recognizable in medias res?

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 14 '05 #3


Craig wrote:
Hello friends at comp.lang.c,

I'm trying to combine 2 strings with a newline character at the end to write
to a file. When I view the file, the messages run together and some of the
str string is cut-off. A portion of the code is below. Any help would be
appreciated.

#define MAX_SIZE 256
char str[MAX_SIZE];
char lev[] = "INFO: ";
va_list ap;

va_start(ap, fmt);
vsprintf(str, fmt, ap);
va_end(ap);

strcat(lev, str);


Since lev is an array of 7 characters, appending to it
is flawed. Make lev a large enough array to hold all the characters.
char lev[LARGE_ENOUGH] = "INFO: ";

If you are only concerned with the final goal of getting the strings
to a file, there is no need to combine in a character array and then
copy to a file. Just copy one string to the file, then append to the
file the other string followed by appending the newline character.
This can all be done with one statement using function fprintf.

fprintf(fp,"%s%s\n",string1,string2);

Example:

#include <stdio.h>

#define FNAME "test1.txt"

int main(void)
{
char *s1 = "INFO: ";
char *s2 = "We are go for launch.";
int ch;
FILE *fp;

if((fp = fopen(FNAME,"w+")) != NULL)
{
fprintf(fp,"%s%s\n",s1,s2);
/* to test it */
rewind(fp);
puts("\tReading from the file, the line is:");
for( ; (ch = fgetc(fp)) != EOF; ) putchar(ch);
fclose(fp);
remove(FNAME);
}
return 0;
}
--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #4
Eric Sosman <es*****@acm-dot-org.invalid> writes:
Keith Thompson wrote:
[...]
I'm now going to go off on a tangent.
Speaking of that, I'm curious about something. ISO C defines the
fread() and fwrite() functions, and all the other stuff in <stdio.h>
that operates on FILE*'s. POSIX defines read() and write(), and all
the other stuff that operates on file descriptors (small integers).
Historically, I think that read() and write() are probably as old as,
or older than, fread() and fwrite(); ANSI chose to standardize the
latter, but not the former. Are there any real-world hosted
implementations that support fread() and fwrite() but *don't* also
support read() and write(), or is the historical precedent strong
enough to make read() and write() effectively universal?


The Rationale discusses the C89 committee's thoughts on
the matter. The crux, it appears, is that read() et al. treat
a file as an array of characters, but this treatment is not
appropriate for all systems -- particularly for text files.
On a system where text lines are terminated with a CR/LF pair,
for example, what would be the semantics of lseek()ing to a
point just after the CR and then reading? Is the end-of-line
sequence recognizable in medias res?


The standard fread()/fwrite() system very nearly treats files as
arrays of characters except for the behavior on end-of-line (and
that's only for text mode). lseek() on a text file with CR/LF pairs
presumably behaves similarly to fseek() on the same file opened in
binary mode.

But my question wasn't about the rationale for the choices made in
standardizing one interface but not the other. (Personally I think it
was a good choice; imposing that kind of redundancy on all
implementations doesn't seem like a good idea.) The question was
whether any real-world implementations actually provide
fread()/fwrite() without providing read()/write(). I ask out of idle
curiosity, not out of any intent to use the knowledge for evil.

--
Keith Thompson (The_Other_Keith) 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.
Nov 14 '05 #5
Keith Thompson wrote:

But my question wasn't about the rationale for the choices made in
standardizing one interface but not the other. (Personally I think it
was a good choice; imposing that kind of redundancy on all
implementations doesn't seem like a good idea.) The question was
whether any real-world implementations actually provide
fread()/fwrite() without providing read()/write(). I ask out of idle
curiosity, not out of any intent to use the knowledge for evil.


System vendors have an incentive to support as many
relevant Standards as possible with reasonable effort.
Most systems (for suitable values of "most") make an effort
to support both the C Standard and at least some of the
POSIX Standards, so read() et al. will be available on
about as many (for suitable values of "as many") systems
as fread() and friends.

That said, there certainly exist systems where neither
fread() nor read() is "native." (Open)VMS is one such, or
at least it was so when I last used it not quite a decade
ago. On VMS, fread() was not layered atop read(); both were
emulated semi-independently atop VMS' own file model. (As
it happens, neither C streams nor POSIX files are adequate
models for the semantics of all VMS file types.)

--
Eric Sosman
es*****@acm.org
Nov 14 '05 #6
"Al Bowers" <xa******@rapidsys.com> wrote in message
news:38*************@individual.net...


Craig wrote:
Hello friends at comp.lang.c,

I'm trying to combine 2 strings with a newline character at the end to write to a file. When I view the file, the messages run together and some of the str string is cut-off. A portion of the code is below. Any help would be appreciated.

#define MAX_SIZE 256
char str[MAX_SIZE];
char lev[] = "INFO: ";
va_list ap;

va_start(ap, fmt);
vsprintf(str, fmt, ap);
va_end(ap);

strcat(lev, str);


Since lev is an array of 7 characters, appending to it
is flawed. Make lev a large enough array to hold all the characters.
char lev[LARGE_ENOUGH] = "INFO: ";

If you are only concerned with the final goal of getting the strings
to a file, there is no need to combine in a character array and then
copy to a file. Just copy one string to the file, then append to the
file the other string followed by appending the newline character.
This can all be done with one statement using function fprintf.

fprintf(fp,"%s%s\n",string1,string2);

Example:

#include <stdio.h>

#define FNAME "test1.txt"

int main(void)
{
char *s1 = "INFO: ";
char *s2 = "We are go for launch.";
int ch;
FILE *fp;

if((fp = fopen(FNAME,"w+")) != NULL)
{
fprintf(fp,"%s%s\n",s1,s2);
/* to test it */
rewind(fp);
puts("\tReading from the file, the line is:");
for( ; (ch = fgetc(fp)) != EOF; ) putchar(ch);
fclose(fp);
remove(FNAME);
}
return 0;
}
--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/


Thanks for the replies. I should posted my message sooner. I tried
increasing the buffer size but it didn't correct the problem so I decided to
re-write the function using fopen and fprintf. The message is written to
the file properly now except for when it is called by a test program that is
supposed to write 1000 messages. The function only writes messages 0
through 252. Any ideas why all the messages aren't being written and what
to do about it?
Nov 14 '05 #7
In article <11*************@corp.supernews.com>,
Craig <NO****************@highstream.net> wrote:
:I tried
:increasing the buffer size but it didn't correct the problem so I decided to
:re-write the function using fopen and fprintf. The message is written to
:the file properly now except for when it is called by a test program that is
:supposed to write 1000 messages. The function only writes messages 0
:through 252. Any ideas why all the messages aren't being written and what
:to do about it?

Are you using fopen() once per message? If so then my guess would be that
you are not fclose()'ing each after you are done. If you keep opening
files without closing them, you are going to run into an implimentation-
dependant maximum number of files that may be simultaneously open.

It is not uncommon for the limit on the number of open files to be
the one implied by the internal use of a char to store the underlying
descriptor number. On systems with 8 bit characters, that allows at
most 256 open files. 3 descriptors are certain to be in use when
the program starts: standard input, standard output, and standard error.
You observe 252; add 3 and you are at 255. The missing last descriptor
is experimental error ;-)
--
This is not the same .sig the second time you read it.
Nov 14 '05 #8


Craig wrote:
Craig wrote:
Hello friends at comp.lang.c,

I'm trying to combine 2 strings with a newline character at the end to
write
to a file. When I view the file, the messages run together and some of
the
str string is cut-off.

Thanks for the replies. I should posted my message sooner. I tried
increasing the buffer size but it didn't correct the problem so I decided to
re-write the function using fopen and fprintf. The message is written to
the file properly now except for when it is called by a test program that is
supposed to write 1000 messages. The function only writes messages 0
through 252. Any ideas why all the messages aren't being written and what
to do about it?

You need to provide the code, at least for the function you mention.

In general, I think you will want to:
1. Open the file for writing.
2. write the 1000 lines to the file with fprintf, or the function
you mentioned.. Check the return value of fprintf in order to
catch a file write error.
3. close the file.

Example:

#include <stdio.h>

#define FNAME "test1.txt"

int WriteData(FILE *fp,const char *s1, const char *s2)
{
return fprintf(fp,"%s%s\n",s1,s2);
}

int main(void)
{
char *s1 = "Test Message Line", info[32];
int ch,i;
FILE *fp;

if((fp = fopen(FNAME,"w+")) != NULL)
{
for(i = 0; i < 1000; i++)
{
sprintf(info,"%s %d",s1,i+1);
if(0 > WriteData(fp,"INFO: ", info)) break;
}
/* to test it */
rewind(fp);
if(i != 1000) puts("Oops! A File Write Error");
else
{
for( ; (ch = fgetc(fp)) != EOF; ) putchar(ch);
puts("END OF FILE");
}
fclose(fp);
remove(FNAME);
}
else puts("Unable to open file for update");
return 0;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #9
"Al Bowers" <xa******@rapidsys.com> wrote in message
news:38*************@individual.net...


Craig wrote:
Craig wrote:

Hello friends at comp.lang.c,

I'm trying to combine 2 strings with a newline character at the end to


write
to a file. When I view the file, the messages run together and some of


the
str string is cut-off.

Thanks for the replies. I should posted my message sooner. I tried
increasing the buffer size but it didn't correct the problem so I decided to re-write the function using fopen and fprintf. The message is written to the file properly now except for when it is called by a test program that is supposed to write 1000 messages. The function only writes messages 0
through 252. Any ideas why all the messages aren't being written and what to do about it?

You need to provide the code, at least for the function you mention.

In general, I think you will want to:
1. Open the file for writing.
2. write the 1000 lines to the file with fprintf, or the function
you mentioned.. Check the return value of fprintf in order to
catch a file write error.
3. close the file.

Example:

#include <stdio.h>

#define FNAME "test1.txt"

int WriteData(FILE *fp,const char *s1, const char *s2)
{
return fprintf(fp,"%s%s\n",s1,s2);
}

int main(void)
{
char *s1 = "Test Message Line", info[32];
int ch,i;
FILE *fp;

if((fp = fopen(FNAME,"w+")) != NULL)
{
for(i = 0; i < 1000; i++)
{
sprintf(info,"%s %d",s1,i+1);
if(0 > WriteData(fp,"INFO: ", info)) break;
}
/* to test it */
rewind(fp);
if(i != 1000) puts("Oops! A File Write Error");
else
{
for( ; (ch = fgetc(fp)) != EOF; ) putchar(ch);
puts("END OF FILE");
}
fclose(fp);
remove(FNAME);
}
else puts("Unable to open file for update");
return 0;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/


Thanks, I just needed the fclose(fp); in the function.
Nov 14 '05 #10

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

Similar topics

1
by: Jack Smith | last post by:
Can some one help me with this proof? Let L be the language of strings over {a,b} recursively defined by the following set of rules (i) the string ^ is in L (^ is the null string). (ii) for...
5
by: ArShAm | last post by:
Hi there Please help me to optimize this code for speed I added /O2 to compiler settings I added /Oe to compiler settings for accepting register type request , but it seems that is not allowed...
3
by: Mahmood Ahmad | last post by:
Hello, I have written a program that reads three types of records, validates them acording to certain requirements and writes the valid records into a binary file. The invalid records are...
0
by: Jon | last post by:
We have a asp.net app that runs like the following in a single-site scenario. Directory structure: c:\inetpub\wwwroot\myapp - aspx files, global.asax and web.config c:\inetpub\wwwroot\myapp\bin...
9
by: Diane | last post by:
Could you please explain me how can I output nested strings? Here is an example: "adsd{rfkm}xcv" The output should start from the inner parentheses, such as: dfF rfkm
4
by: WaterWalk | last post by:
Hello, I'm currently learning string manipulation. I'm curious about what is the favored way for string manipulation in C, expecially when strings contain non-ASCII characters. For example, if...
4
by: Robin Haswell | last post by:
Okay I'm getting really frustrated with Python's Unicode handling, I'm trying everything I can think of an I can't escape Unicode(En|De)codeError no matter what I try. Could someone explain to...
2
by: almurph | last post by:
Hi, Hope you can help me. This is a trick one - at least I think so. I have 2 strings. I have to calculate the "score" of the strings. Score is determined by matching patterns of letters within...
4
by: Debbiedo | last post by:
My software program outputs an XML Driving Directions file that I need to input into an Access table (although if need be I can import a dbf or xls) so that I can relate one of the fields...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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...
1
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...
0
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...
0
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,...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.