[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 644
  • Last Modified:

Trying to add a character and strings to a char array or char * in C but failing.

Hi there;

I have several problems

1) expanding an char array (or should I expand)
2) I am trying to add a character to a string value. It's straight forward but I fail.

# include <stdio.h>
# include <string.h>
# include <time.h>
# include <stdlib.h>
char * construct();

void main()
{	
	int filesize = 50000;	
	int bufflen = 50 * 1024;
	int strsize;
	char * buffer = new char[bufflen];	
	char *randstr = construct();

	*buffer = '\0';
	
	strsize = strlen(randstr);
	int actual;
	while (bufflen >= 0) {
		strcat(buffer, randstr);
		actual = bufflen;
		bufflen -= strsize;  
		if(bufflen <= 0)  
			break;

	}
	bufflen = actual;
	FILE *pfile = fopen("bigfile.txt","wt");
	for(int i=0; i < filesize/bufflen;i++)
	{
		fwrite(buffer, 1, bufflen, pfile);
	}
	fclose(pfile);
}

char randCharacter()
{
	char randChar = ' ';
	int counter = 0;
	int randNum = 0;

	// Provide seed for the random number
	// generator.
	srand(time(NULL));
	//for (counter = 0; counter < 10; counter++)
	{
		// First, pick a number between 0 and 
		// 25.
		randNum = 26 * (rand() / (RAND_MAX + 1.0));

		// The ASCII code for 'A' is 65, so
		// add 97 to the random number to get
		// a lower case letter.
		randNum = randNum + 65;

		// Type cast to character to convert
		// it to a char type.
		randChar = (char) randNum;

	}
	//printf ("Random char: %s\n", randChar);
	return randChar;
}


char * construct()
{		
	char randstr[20] = "ABCDEFGHIJ";
	
	strcat(randstr, "X"); //Actually planning to append a char first, from randCharacter function

	printf("Rand:%s\n", randstr);
	printf("Len: %d\n", strlen(randstr));
	printf("ten: %c\n", randstr[10]);
//Outputs correctly in console but writes the first 6 to the file.

	//strcat(randstr, "12 1.5\n"); Int and double values are actually dynamically generated
	//strcat(randstr, "43 1.8\n");
	
	return randstr;
}

Open in new window


This question is a linked question:
http://www.experts-exchange.com/Programming/Languages/C/Q_28013850.html

Regards.
0
jazzIIIlove
Asked:
jazzIIIlove
  • 6
  • 4
  • 3
5 Solutions
 
Julian HansenCommented:
Firstly I would use the following to generate your random upper case char.
char c = (char)((rand() % 26) + 65);

Open in new window


Other than that - not sure where it is failing - what does it do that it shouldn't or not do that it should
0
 
ozoCommented:
Did you notice any error messages when you tried to compile it?

try changing

 char * buffer = malloc(bufflen);


        static char randstr[20] = "ABCDEFGHIJ";
0
 
jazzIIIloveAuthor Commented:
ok, my mistake. The question wasn't clear. It's running, no compile errors. but what I actually need is:

i am using strcat to concatanate "ABCDEFGHIJ". i cannot concatanate a char 'X', so i think i need to convert and concat.
char c = (char)((rand() % 26) + 65); //credit to : julianH.

strcat(randstr, "X"); //Actually planning to append a char---> not a string char.


My other actual problem is in the comments:
//strcat(randstr, "12 1.5\n"); Int and double values are actually dynamically generated
//strcat(randstr, "43 1.8\n");

randstr has an original value, now added a character and now I need expand the randstr more to add the int and float looking values. What is the elegant way of doing this?

Regards.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
ozoCommented:
You should have gotten an error about 'new' being undeclared, if not a warning about returning the address of local variable.

But after those are fixed,

You subtract a strsize of 11 from a bufflen of 51200
4654 times, leaving a bufflen = actual of 6,
so each
    fwrite(buffer, 1, bufflen, pfile);
only writes 6 bytes at a time.
0
 
jazzIIIloveAuthor Commented:
Hi;

I am trying to form a big file with a pattern. I really don't get an error in new part, but failed to concat a char as a char to a string since randstr[20] is fixed, it should be expanding as I am not only planning to concat a char but also other strings to form the file content but failed.


void main()
{	
	int filesize = 50000;	
	int bufflen = 50 * 1024;
	int strsize;
	char * buffer = new char[bufflen];	
	char *randstr = construct();

	*buffer = '\0';
	
	strsize = strlen(randstr);
	int actual;
	
	while (bufflen >= 0) {
		strcat(buffer, randstr);
		actual = bufflen;
		bufflen -= strsize;  
		if(bufflen <= 0)  
			break;
	}

	bufflen = actual;
	
	FILE *pfile = fopen("bigfile.txt","wt");
	for(int i=0; i < filesize/bufflen;i++)
	{
		fwrite(buffer, 1, strlen(randstr), pfile);
	}
	fclose(pfile);
}


char * construct()
{		
	char randstr[20] = "ABCDEFGHIJ";
	
	char c = (char)((rand() % 26) + 65);

	strcat(randstr, "X"); //Actually planning to append a char first, from randCharacter function

	printf("Rand:%s\n", randstr);
	printf("Len: %d\n", strlen(randstr));
	printf("ten: %c\n", randstr[10]);
//Outputs correctly in console but writes the first 6 to the file.

	//strcat(randstr, "12 1.5\n"); Int and double values are actually dynamically generated
	//strcat(randstr, "43 1.8\n");
	
	return randstr;
}

Open in new window


Regards.
0
 
jazzIIIloveAuthor Commented:
Hi;

Here is my finalized code. I have stuck currently in the idea of outer loop of construct() function. If I don't use a loop I can print out but I need loop over alphabet letters.

I also tried to call the function in a loop, but then the buffer construction is lost. Following is the final complete code:

# include <stdio.h>
# include <string.h>
# include <time.h>
# include <stdlib.h>
# include <math.h>
char * construct();

void main()
{	
	int filesize = 50000;	
	int bufflen = 50 * 1024;
	int strsize;
	char * buffer = new char[bufflen];
	char *randstr = construct();

	*buffer = '\0';

	strsize = strlen(randstr);
	int actual;

	while (bufflen >= 0) {
		strcat(buffer, randstr);
		actual = bufflen;
		bufflen -= strsize;  
		if(bufflen <= 0)  
			break;
	}

	bufflen = actual;

	FILE *pfile = fopen("bigfile.txt","wt");
	for(int i=0; i < filesize/bufflen;i++)
	{
		fwrite(buffer, 1, strlen(randstr), pfile);
	}
	fclose(pfile);
}

double truncateDouble(double x, int digits)
{
	double f=pow(10.0, digits);
	return ((int)(x*f))/f;
}

char * construct()
{		
	
	static char randstr [1000000] = "Operator ";
	srand(time(NULL));
	for(int m = 65; m <=90; m++)
	{				
		//char c = (char)((rand() % 26) + 65);
		char c =m++;
		randstr[9] = c;
		randstr[10] = ':';
		randstr[11] = '\n';

		
		int j = 0;
		int r[50];
		double p[50];
		double tr[50];
		for(int i = 1000; i < 20000; i+=1000)
		{
			r[j] = rand() % i + 10;
			p[j] = ((double)(rand() % i)/(double)RAND_MAX+rand() % (j+1));	 

			char integer_string[32];
			sprintf(integer_string, "%d", r[j]);

			char double_string[32];
			sprintf(double_string, "%.2f", p[j]);

			strcat(randstr, integer_string);
			strcat(randstr, " \t");
			strcat(randstr, double_string);
			strcat(randstr, "\n");
			j++;
		}
		strcat(randstr, "\n");										
	}	
	strcat(randstr, "\0");										
	return randstr;
}

Open in new window

0
 
jazzIIIloveAuthor Commented:
Hi;

I made the code finally working but I am afraid the code quality sucks..Can anyone inform me what to do to make this code better?

My aim is to populate the file to a huge size within the
for(int i = 0; i < filesize/100;i++)

Open in new window

loop. This is also related with the question link in this question.

# include <stdio.h>
# include <string.h>
# include <time.h>
# include <stdlib.h>
# include <math.h>
# define filesize 50000

char * construct(char c, int bufflen);

void main()
{		
	int strsize;

	FILE *pfile = fopen("bigfile.txt","wt");		 
	int m = 65;
	srand(time(NULL));
	for(int i = 65; i <= 90;i++)
	{
		int bufflen = 50 * 1024;	
		char * buffer = new char[bufflen];
		*buffer = '\0';
		char * randstr = construct(i, bufflen);
		strsize = strlen(randstr);

		bufflen = strsize;	
		fwrite(randstr, 1, bufflen, pfile);

	}
	fclose(pfile);
}

char * construct(char c,int bufflen)
{		
	char randstr[1000000] = "Operator ";	

	randstr[9] = c;
	strcat(randstr,":\n");

	for(int i = 0; i < filesize/100;i++)
	{
		int j = 0;
		int r[50];
		double p[50];
		double tr[50];
		for(int i = 1000; i < 20000; i+=1000){
			r[j] = rand() % i + 10;
			p[j] = ((double)(rand() % i)/(double)RAND_MAX+rand() % (j+1));	 	

			char integer_string[32];
			sprintf(integer_string, "%d", r[j]);

			char double_string[32];
			sprintf(double_string, "%.2f", p[j]);
			strcat(randstr, integer_string);
			strcat(randstr, " \t");
			strcat(randstr, double_string);
			strcat(randstr, "\n");
			j++;
		}	
	}
	return randstr;
}

Open in new window


Regards.
0
 
ozoCommented:
One problem is that your construct function is still returning the address of a local variable.
to avoid undefined behaviour, you should make randstr static, or else allocate it.
0
 
Julian HansenCommented:
Suggestion - close one of your questions and focus on the other - essentially they are focusing on the same thing.
0
 
ozoCommented:
It is not clear why r and p should be arrays, nor what tr is for.
And what's the purpose of
int m = 65;
or of
 bufflen = strsize;

and why is bufflen passed to construct?
0
 
Julian HansenCommented:
I think the above are legacy hold overs from a progessive journey of discovery.

I asked similar questions in the other post - hence the suggestion the two be combined - duplicating effort here.
0
 
jazzIIIloveAuthor Commented:
:/

Terribly sorry, actually i didn't mean to duplicate but it really looks like a duplication.

Ok I grade the most of points to you for other question, and most of points here to Ozo.

Regards.
0
 
jazzIIIloveAuthor Commented:
Ozo, let's continue from the other question.

Regards.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 6
  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now