Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why do I get the wrong strring?

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Its simple yet, deosn't work:

FILE *dfd;
char m[1000];
char xyzst [100];

dfd=fopen("dtance","r");
fgets(m,1000,dfd);

strcat(xyzst,"playprompt");
printf("%s\nl",xyzst);

generates the following '123329playprompt ' instead of 'playprompt123329'.
The file dtance contains on one line '123329'.

 
The code above just prints "playprompt" (followed by a new line and then an 'l' -- it is \n not \nl for new line BTW).
Not sure what the problem is exactly (I have a feeling there's a typo there), in any case, here's some code that will do what I _think_ you want to do with a few comments thrown in:

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

#define PROMPT_SIZE 100

int main(void)
{

FILE *dfd;
/* m doesn't need to be bigger than xyzst */
char m[PROMPT_SIZE+1]; /* +1 to allow for terminating null */
char xyzst [PROMPT_SIZE+1]; /* same here */

strcpy(xyzst,&quot;playprompt&quot;);

/* always want to check return value of fopen() */
if ((dfd=fopen(&quot;dtance&quot;,&quot;r&quot;))==NULL) {
perror(&quot;file open failure&quot;);
return EXIT_FAILURE;
}

if (fgets(m,sizeof(m),dfd)==NULL) {
fprintf(stderr,&quot;failed to get data, empty file?\n&quot;);
return EXIT_FAILURE;
} else {
/* make sure the value from the file will fit */
if (strlen(m) > (PROMPT_SIZE-strlen(xyzst))) {
fprintf(stderr,&quot;prompt %s too long\n&quot;,m);
return EXIT_FAILURE;
} else {
strcat(xyzst,m);
/* fgets() adds the newline to the string for us */
printf(&quot;%s&quot;,xyzst);
}
}
return EXIT_SUCCESS;
}

HTH,
[sig]<p>Russ<br><a href=mailto:bobbitts@hotmail.com>bobbitts@hotmail.com</a><br><a href= is in</a><br>[/sig]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top