Solved

Problems in adding file

Posted on 2011-02-24
46
336 Views
Last Modified: 2012-05-11
Hi all,
I was having problem in output the data. I dunno where goes wrong in my code... but i think is in the addFile func or main func! the prog is asked the user to input a filename and that file will add into my database file and then perform sorting and search (there already exist some data in the database with AC1.txt) any help will be greatly appreciated:)
#include	<stdio.h>
#include 	<string.h>
#include 	<stdlib.h>
#include 	"ourhdr.h"

typedef struct				// Country Data struct declaration
    	{  	
		char code[4]; 		// Country Code 
       		char name[50];		// Country Name
		float life_expectancy;	// Life Expentancy of the Country's citizen
		int pop;		// Country's Population
    	} DATATYPE;

typedef struct				// Index Data struct declaration
	{
		char code[4];		
		long int offset;	// offset of the data
	} INDEX;

INDEX StructArray[300];	// for a lot of them
DATATYPE ActualStruct; // for a single struct
DATATYPE DatabaseArray[300]; 	// DATATYPE array

/***********************Index Copy function************************************************/

void indexCopy(INDEX* dest, INDEX src)
{
  strcpy(dest->code, src.code);
  dest->offset = src.offset;
} 

/*************************Insertion Sort function******************************************/

void sort(INDEX SortArray[], int n)
{
	int j;
	for(j=0; j < n;j++)
	{
		int k;
		INDEX temp; //Create a blank index data object
                indexCopy(&temp, SortArray[j]); //copy the data from the current line
		k = j-1;
		while (strcmp(SortArray[k].code, temp.code) >= 0 && k>=0)
		{
			indexCopy(&SortArray[k+1], SortArray[k]); //Now move them over
			k = k - 1;
		}
		indexCopy(&SortArray[k+1], temp);//And move the temp one back in
	}
} 

/*************************Print Sorted Array**********************************************/
void printsort(int size)
{
                      DATATYPE country;

	sort(StructArray,size);	// call sort function
	FILE *FI;
	if((FI = fopen("DATABASE.txt", "r")) == NULL) // open DATABASE for read
    		err_sys("Open DATABASE Fail\n");
	int i;
	printf("--------------------------------------------------------------------------------------------------------\n");
	printf("  CODE \t\t\t COUNTRY NAME \t\t\t   POPULATION      LIFE EXPECTANCY \t OFFSET\n");
	printf("--------------------------------------------------------------------------------------------------------\n");
	
	for (i=0; i<size; i++)
	{	
              	fseek(FI,StructArray[i].offset,SEEK_SET);	//seek the offset in the binary file
               	fread(&country, sizeof(DATATYPE),1,FI);	// read the struct of array from binary file (4 fields)
		printf("%5s%50s%15u%18f%15u\n", country.code, country.name, country.pop, country.life_expectancy, StructArray[i].offset);
	}
} 

/************************Search Function by Country Code*********************************/
void search(int size)
{
	int mid, lower = 0, upper = size, flag = 1;
	INDEX cc;
	FILE *FI;
	if((FI = fopen("DATABASE.txt", "r")) == NULL) // open DATABASE for read
    		err_sys("Open DATABASE Fail\n");
	printf("Enter Country Code to search: ");
	scanf("%s", &cc);

	for(mid = (lower+upper)/2; lower <= upper; mid = (lower + upper)/2)
	{
		if(strcmp(StructArray[mid].code, cc.code) == 0)		// compare the input with the sorted array
		{
			printf("The country code is at position %d in the array at offset %u in the binary file.\n", mid, StructArray[mid].offset);
                        fseek(FI,StructArray[mid].offset,SEEK_CUR);	//seek the offset in the binary file
                        fread(&DatabaseArray[mid], sizeof(DATATYPE),1,FI);	// read the struct of array from binary file (4 fields)
			printf("%s %s %u %f\n", DatabaseArray[mid].code, DatabaseArray[mid].name, DatabaseArray[mid].pop, DatabaseArray[mid].life_expectancy);
			flag = 0;
			break;
		}
		if(strcmp(StructArray[mid].code, cc.code) > 0)		// compare the input with the sorted array
			upper = mid - 1;
		else
			lower = mid + 1;
	}
	
	if (flag)
		printf("Elements not found.");				// print this if the input is not in the array	

	if (fclose(FI))				// close file descriptor FI
		err_sys("Close error\n");
}

/****************************Add File***********************************************/

int addFile(DATATYPE* Array2, char* filename, int startHere)
{
	int i = startHere;	
	int size = startHere;
	char * Tok;         // token from line
	FILE *FI, *FO, *FO2;
	char Line[1000];  // NO input line (delimited by \n) is longer than 1000

	if((FI = fopen(filename, "r")) == NULL) // open a stream from "countries"
    		err_sys("Open Fail\n");

	if((FO = fopen("DATABASE.txt", "a")) == NULL) // open a stream from "countries"
    		err_sys("Open DATABASE Fail\n");

	if((FO2 = fopen("DIRECTORY.txt", "a")) == NULL) // open a stream from "countries"
    		err_sys("Open DIRECTORY Fail\n");

    while ( fgets( (char *) Line,1000,FI) != NULL) // fill buffer up to newline or eof or error
    {

	Tok = strtok( Line ,",\n"); 	// skip ID number

        Tok = strtok( NULL ,",\n"); 	// this should get the country code 
        ActualStruct.code[0] = Tok[0];
        ActualStruct.code[1] = Tok[1];
        ActualStruct.code[2] = Tok[2];
        ActualStruct.code[3] = 0; 	// To create "string" 

	Tok = strtok( NULL ,",\n"); 	// this should get the country name 
        strncpy(&ActualStruct.name[0],Tok,50);	// copy string at most 50 chars

	Tok = strtok( NULL ,",\n"); 	// skip
	Tok = strtok( NULL ,",\n"); 	// skip 
	Tok = strtok( NULL ,",\n"); 	// skip
	Tok = strtok( NULL ,",\n"); 	// skip 

	Tok = strtok( NULL ,",\n"); 	// this should get the population
	ActualStruct.pop = atoi(Tok);	// convert string to integer

        Tok = strtok( NULL ,",\n"); 	// this one should get life expectancy
        ActualStruct.life_expectancy = atof(Tok);	// convert string to a floating point number

	strcpy(Array2[i].code,ActualStruct.code);	// get the current code 
	strcpy(Array2[i].name,ActualStruct.name);	// get the current name
	Array2[i].pop = ActualStruct.pop;		// get the current population
	Array2[i].life_expectancy = ActualStruct.life_expectancy; // get the current life expectancy

	strcpy(StructArray[i].code, ActualStruct.code);	// get the current code 
	StructArray[i].offset = ftell(FO);             	// get the current offset in the DATABASE file 

	if (fwrite(&Array2[i], sizeof(DATATYPE),1,FO) != 1)  // write the struct to the DATABASE file 
		err_sys("fwrite error");

	i++;
	size = i;
	}

/****************************Sort the array and write into DIRECTORY*****************************/

	sort(StructArray,size);	// call sort function
	
	for (i=0; i<size; i++)
	{	
		if (fwrite(&StructArray[i], sizeof(INDEX),1,FO2) != 1)  // write the struct to the DIRECTORY file 
			err_sys("fwrite error");
	}

	if (fclose(FI))				// close file descriptor FI
		err_sys("Close error\n");	
	if (fclose(FO))				// close file descriptor FO
		err_sys("Close error\n");	
	if (fclose(FO2))			// close file descriptor FO2
		err_sys("Close error\n");

}
/****************************************Main Function********************************************/

int main() 
{ 
  	char userfile[50];
  	int count = 0;
	int size = 0;
	count = addFile(DatabaseArray,"AC1.txt",0);

/***********************************read DIRECTORY file into memory******************************/

	FILE *infile;		// declare an index file pointer
	char *buffer;
	long numbytes;

	if((infile = fopen("DIRECTORY.txt", "rb")) == NULL) // open a stream from "countries"
    		err_sys("Open DIRECTORY Fail\n");

	fseek(infile,0,SEEK_END);
	numbytes = ftell(infile);	// get the number of bytes
	
	fseek(infile,0, SEEK_SET);	// reset the file position indicator to the beginning of the file

	buffer = (char*)calloc(numbytes,sizeof(char)); 	// grab sufficient memory for the buffer 
							// to hold the text

	fread(buffer,sizeof(char),numbytes,infile);	// copy all the text into the buffer
	fclose(infile);

	free(buffer);	// free the memory we used for the buffer
	
/*********************************************MENU************************************************/

	int c = -1;
	while( c != 4)
	{
		printf("Please select an option (1 to 4):\n");
		printf("1. Add to the DATABASE\n");
		printf("2. Search the DATABASE\n");
		printf("3. List all the countries in DATABASE by ordered Country Code\n");
		printf("4. Press q to exit\n");
		fflush(stdin);
		c = -1;		// error value if scanf fails
		scanf("%d", &c);
		switch (c)
		{
			case 1:
                                printf("Filename(data that you would like to add in): ");
				scanf("%s",&userfile);
				count = addFile(DatabaseArray, userfile, count);
				break;
			case 2:
				search(size);
				break;
			case 3: 
				printsort(size);
				break;
			case 4:
				puts("Exiting program!");
				return 0;
			default:
				printf("\nNot implemented yet!");
		}
	}
}

Open in new window


the output is nothing

Please select an option (1 to 4):
1. Add to the DATABASE
2. Search the DATABASE
3. List all the countries in DATABASE by ordered Country Code
4. Press 4 to exit
3
--------------------------------------------------------------------------------------------------------
  CODE                   COUNTRY NAME                      POPULATION      LIFE EXPECTANCY       OFFSET
--------------------------------------------------------------------------------------------------------

0
Comment
Question by:crazy4s
  • 26
  • 20
46 Comments
 
LVL 32

Expert Comment

by:phoffric
ID: 34976566
I don't think you posted the correct version since
111: addFile says it returns an int, but there is no return.
193: count = addFile()
0
 

Author Comment

by:crazy4s
ID: 34976583
hmm so do you meant i should put a return ()at the end of the addFile func?
what should i return? do i return the count?
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34976611
I'd like to know how you got the output since without the return, the the compiler gives an error.

Is the addFile function part of your design? If so, what is your intent? Why did you say it returns an int?And later at line 193, you actually do use the return value.

Now, I haven't tried to study your entire application. I just noted that it would not compile, and wondered how you were able to get any output at all.
0
 

Author Comment

by:crazy4s
ID: 34976649
well it doesn't give me any error but is just don't have any output...
actually originally i have a file which is AC1.txt(csv file) and so the prog will read this data, write into binary file(all the four fields) get the offsets, sort it by array and write it to the directory file(country code with offset). And if the user choose option 1 to add a new file into database (this prog have to append the new file to the existing file which is already in the database) and sort it and then write it back again to the directory file.
this question was previously asked in this section too but it seems to have no reply so i start a new question here again:(
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34976952
>> but it seems to have no reply so i start a new question
When starting a related question, then after closing the previous question you should hit the "ask a related question" link that becomes available. Then the questions are cross-referenced with each other.

===

What OS and compiler are you using? I don't understand why you don't get an error when your function doesn't return a required int.

====
>> do you meant i should put a return () at the end of the addFile func?
>> what should i return?
>> do i return the count?

Maybe you answered my question, but I didn't follow (sorry). Here are my questions:
1. Is the addFile function part of your design?
2. Why did you say that addFile function returns an int?
3. And later at line 193, you actually do use the return value. So, why don't you know what the addFile function is supposed to return?
0
 

Author Comment

by:crazy4s
ID: 34976965
i'm using UNIX.
http://www.experts-exchange.com/Programming/Languages/C/Q_26835236.html this is previously the post that i asked about the same question. well at first i was using void but i got an error for it and he said to use int...n there he lead me till this code.
0
 

Author Comment

by:crazy4s
ID: 34976970
sorry i was new here so not very familiar with the stuffs! anyway thanks for the suggestion:)
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34977020
>> well at first i was using void but i got an error for it and he said to use int...n
Ok, I probably understand why you got an error.
You have at line 193:
     count = addFile(DatabaseArray,"AC1.txt",0);
and then later you use this count also in addFile.

This means that addFile is returning a count of something. What is this something? Whatever it is, then your function should return that item.

Now, since your addFile is not returning anything explicitly, I can only guess that it is returning garbage (or maybe even 0). So, let me know what value of count are your getting everytime you return from addFile. Since you have a clear error in your program, there is a reasonable chance that this confusion may be related to your prolbem.

What GUI debugger is available to you? Have you taken the time to learn how to use a GUI debugger as I recommended last week? You will save so much time if you do that.

Now, here is what you should do. Step through the debugger, and when you hit the option 3 (as in your OP), then determine what are the values of the parameters that go into the function you are calling. When you figure that out, post what you have found. Then step into that function and see how those values affect the results you are getting.

0
 

Author Comment

by:crazy4s
ID: 34977126
because i need to append the new file to the end of file of the existing file everytime i add new data, i think that's what the count he meant to be. to calculate somekind like the position it supposed to be.
hmm i made a break point at addFile and then run but when it comes to the option i choose 3 they just output the empty file, hmmm not sure how to check starting from here?
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34977151
I found a file from one of your previous questions. I was wondering whether the below output is what you are hoping to get?

>> hmm i made a break point at addFile and then run
When you run, you skip all the interesting details. As I explained once before, there are two really important things you can do with your debugger after breaking. You can step through the code to make sure that you are going where you expect to go; and you can look at the values of variables.

Specifically, in this case, I suggested:

let me know what value of count are your getting everytime you return from addFile. Since you have a clear error in your program, there is a reasonable chance that this confusion may be related to your prolbem.

Step through the debugger, and when you hit the option 3 (as in your OP), then determine what are the values of the parameters that go into the function you are calling. When you figure that out, post what you have found. Then step into that function and see how those values affect the results you are getting.

After you hit the breakpoint in addFile, do not enter r (for run). Either enter n (for next) or an s (for step into a function).

Please select an option (1 to 4):
1. Add to the DATABASE
2. Search the DATABASE
3. List all the countries in DATABASE by ordered Country Code
4. Press q to exit
3
--------------------------------------------------------------------------------------------------------
  CODE                   COUNTRY NAME                      POPULATION      LIFE EXPECTANCY       OFFSET
--------------------------------------------------------------------------------------------------------
  AGO                                            Angola       12878000         38.299999           1408
  BDI                                            BWAola       12878000         38.299999           1728
  BEN                                           BENeria       31471000         69.699997           1472
  BFA                                            BFAola       12878000         38.299999           1664
  BWA                                            BWAola       12878000         38.299999           1536
  DZA                                           Algeria       31471000         69.699997              0
  IOT                                            IOTola       12878000         38.299999           1600

Open in new window

0
 

Author Comment

by:crazy4s
ID: 34977163
when i hit n after making the break point at addFile i got this
(gdb) b addFile
Breakpoint 1 at 0x1127c: file sort1.c, line 113.
(gdb) n
The program is not being run.

yeah that's the output i want...but because i need to make an addFile func and here it comes the error:(
0
 

Author Comment

by:crazy4s
ID: 34977173
hmm the output should be something like that

--------------------------------------------------------------------------------------------------------
  CODE                   COUNTRY NAME                      POPULATION      LIFE EXPECTANCY       OFFSET
--------------------------------------------------------------------------------------------------------
  AGO                                            Angola       12878000         38.299999             64
  BDI                                           Burundi        6695000         46.200001            384
  BEN                                             Benin        6097000         50.200001            128
  BFA                                      Burkina Faso       11937000         46.700001            320
  BWA                                          Botswana        1622000         39.299999            192
  DZA                                           Algeria       31471000         69.699997              0
  IOT                    British Indian Ocean Territory              0          0.000000            256

the code before the addFile func added to it is
#include	<stdio.h>
#include 	<string.h>
#include 	<stdlib.h>
#include 	"ourhdr.h"

typedef struct				// Country Data struct declaration
    	{  	
		char code[4]; 		// Country Code 
       		char name[50];		// Country Name
		float life_expectancy;	// Life Expentancy of the Country's citizen
		int pop;		// Country's Population
    	} DATATYPE;

typedef struct				// Index Data struct declaration
	{
		char code[4];		
		long int offset;	// offset of the data
	} INDEX;

INDEX StructArray[300];	// for a lot of them
DATATYPE ActualStruct; // for a single struct
DATATYPE DatabaseArray[300]; 	// DATATYPE array

/***********************Index Copy function************************************************/

void indexCopy(INDEX* dest, INDEX src)
{
  strcpy(dest->code, src.code);
  dest->offset = src.offset;
} 

/*************************Insertion Sort function******************************************/

void sort(INDEX SortArray[], int n)
{
	int j;
	for(j=0; j < n;j++)
	{
		int k;
		INDEX temp; //Create a blank index data object
                indexCopy(&temp, SortArray[j]); //copy the data from the current line
		k = j-1;
		while (strcmp(SortArray[k].code, temp.code) >= 0 && k>=0)
		{
			indexCopy(&SortArray[k+1], SortArray[k]); //Now move them over
			k = k - 1;
		}
		indexCopy(&SortArray[k+1], temp);//And move the temp one back in
	}
} 

/*************************Print Sorted Array**********************************************/
void printsort(int size)
{
                      DATATYPE country;

	sort(StructArray,size);	// call sort function
	FILE *FI;
	if((FI = fopen("DATABASE.txt", "r")) == NULL) // open DATABASE for read
    		err_sys("Open DATABASE Fail\n");
	int i;
	printf("--------------------------------------------------------------------------------------------------------\n");
	printf("  CODE \t\t\t COUNTRY NAME \t\t\t   POPULATION      LIFE EXPECTANCY \t OFFSET\n");
	printf("--------------------------------------------------------------------------------------------------------\n");
	
	for (i=0; i<size; i++)
	{	
              	fseek(FI,StructArray[i].offset,SEEK_SET);	//seek the offset in the binary file
               	fread(&country, sizeof(DATATYPE),1,FI);	// read the struct of array from binary file (4 fields)
		printf("%5s%50s%15u%18f%15u\n", country.code, country.name, country.pop, country.life_expectancy, StructArray[i].offset);
	}
} 

/************************Search Function by Country Code*********************************/
void search(int size)
{
	int mid, lower = 0, upper = size, flag = 1;
	INDEX cc;
	FILE *FI;
	if((FI = fopen("DATABASE.txt", "r")) == NULL) // open DATABASE for read
    		err_sys("Open DATABASE Fail\n");
	printf("Enter Country Code to search: ");
	scanf("%s", &cc);

	for(mid = (lower+upper)/2; lower <= upper; mid = (lower + upper)/2)
	{
		if(strcmp(StructArray[mid].code, cc.code) == 0)		// compare the input with the sorted array
		{
			printf("The country code is at position %d in the array at offset %u in the binary file.\n", mid, StructArray[mid].offset);
                        fseek(FI,StructArray[mid].offset,SEEK_CUR);	//seek the offset in the binary file
                        fread(&DatabaseArray[mid], sizeof(DATATYPE),1,FI);	// read the struct of array from binary file (4 fields)
			printf("%s %s %u %f\n", DatabaseArray[mid].code, DatabaseArray[mid].name, DatabaseArray[mid].pop, DatabaseArray[mid].life_expectancy);
			flag = 0;
			break;
		}
		if(strcmp(StructArray[mid].code, cc.code) > 0)		// compare the input with the sorted array
			upper = mid - 1;
		else
			lower = mid + 1;
	}
	
	if (flag)
		printf("Elements not found.");				// print this if the input is not in the array	

	if (fclose(FI))				// close file descriptor FI
		err_sys("Close error\n");
}
	

/***************************Main Function********************************************/

int main(int argc, char *argv[]) 
{ 
	int i = 0;
	int size = 0;
	FILE *FI, *FO, *FO2;
	char Line[1000];  // NO input line (delimited by \n) is longer than 1000

	char * Tok;         // token from line
	//if (argc!= 2)
	//	printf("MYAS2 <filename>\n") ;
	
	if((FI = fopen("AC1.txt", "r")) == NULL) // open a stream from "countries"
    		err_sys("Open Fail\n");

	if((FO = fopen("DATABASE.txt", "wb")) == NULL) // open a stream from "countries"
    		err_sys("Open DATABASE Fail\n");

	if((FO2 = fopen("DIRECTORY.txt", "w+")) == NULL) // open a stream from "countries"
    		err_sys("Open DIRECTORY Fail\n");

    while ( fgets( (char *) Line,1000,FI) != NULL) // fill buffer up to newline or eof or error
    {

	Tok = strtok( Line ,",\n"); 	// skip ID number

        Tok = strtok( NULL ,",\n"); 	// this should get the country code 
        ActualStruct.code[0] = Tok[0];
        ActualStruct.code[1] = Tok[1];
        ActualStruct.code[2] = Tok[2];
        ActualStruct.code[3] = 0; 	// To create "string" 

	Tok = strtok( NULL ,",\n"); 	// this should get the country name 
        strncpy(&ActualStruct.name[0],Tok,50);	// copy string at most 50 chars

	Tok = strtok( NULL ,",\n"); 	// skip
	Tok = strtok( NULL ,",\n"); 	// skip 
	Tok = strtok( NULL ,",\n"); 	// skip
	Tok = strtok( NULL ,",\n"); 	// skip 

	Tok = strtok( NULL ,",\n"); 	// this should get the population
	ActualStruct.pop = atoi(Tok);	// convert string to integer

        Tok = strtok( NULL ,",\n"); 	// this one should get life expectancy
        ActualStruct.life_expectancy = atof(Tok);	// convert string to a floating point number

	strcpy(DatabaseArray[i].code,ActualStruct.code);	// get the current code 
	strcpy(DatabaseArray[i].name,ActualStruct.name);	// get the current name
	DatabaseArray[i].pop = ActualStruct.pop;		// get the current population
	DatabaseArray[i].life_expectancy = ActualStruct.life_expectancy; // get the current life expectancy

	strcpy(StructArray[i].code, ActualStruct.code);	// get the current code 
	StructArray[i].offset = ftell(FO);             	// get the current offset in the DATABASE file 

	if (fwrite(&DatabaseArray[i], sizeof(DATATYPE),1,FO) != 1)  // write the struct to the DATABASE file 
		err_sys("fwrite error");

	i++;
	size = i;
	}

/****************************Sort the array and write into DIRECTORY*****************************/

	sort(StructArray,size);	// call sort function
	
	for (i=0; i<size; i++)
	{	
		if (fwrite(&StructArray[i], sizeof(INDEX),1,FO2) != 1)  // write the struct to the DIRECTORY file 
			err_sys("fwrite error");
	}

	if (fclose(FI))				// close file descriptor FI
		err_sys("Close error\n");	
	if (fclose(FO))				// close file descriptor FO
		err_sys("Close error\n");	
	if (fclose(FO2))			// close file descriptor FO2
		err_sys("Close error\n");

/***********************************read DIRECTORY file into memory******************************/

	FILE *infile;		// declare an index file pointer
	char *buffer;
	long numbytes;

	if((infile = fopen("DIRECTORY.txt", "rb")) == NULL) // open a stream from "countries"
    		err_sys("Open DIRECTORY Fail\n");

	fseek(infile,0,SEEK_END);
	numbytes = ftell(infile);	// get the number of bytes
	
	fseek(infile,0, SEEK_SET);	// reset the file position indicator to the beginning of the file

	buffer = (char*)calloc(numbytes,sizeof(char)); 	// grab sufficient memory for the buffer 
							// to hold the text

	fread(buffer,sizeof(char),numbytes,infile);	// copy all the text into the buffer
	fclose(infile);

	free(buffer);	// free the memory we used for the buffer
	
/*********************************************MENU************************************************/

	int c = -1;
	while( c != 4)
	{
		printf("Please select an option (1 to 4):\n");
		printf("1. Add to the DATABASE\n");
		printf("2. Search the DATABASE\n");
		printf("3. List all the countries in DATABASE by ordered Country Code\n");
		printf("4. Press q to exit\n");
		fflush(stdin);
		c = -1;		// error value if scanf fails
		scanf("%d", &c);
		switch (c)
		{
			case 1:
                                printf("Filename(data that you would like to add in): ");
				break;
			case 2:
				search(size);
				break;
			case 3: 
				printsort(size);
				break;
			case 4:
				puts("Exiting program!");
				return 0;
			default:
				printf("\nNot implemented yet!");
		}
	}

}

Open in new window

0
 
LVL 32

Expert Comment

by:phoffric
ID: 34977176
repeating..

http://www.experts-exchange.com/Programming/Languages/Q_26833507.html#a34935604

Then after the break, do not use r again, just n and s.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34977178
Well, let's just focus on seeing if you can get some output; and then another question can be on getting a better output. OK?
0
 

Author Comment

by:crazy4s
ID: 34977179
ya after the break i used n but the prog is not being run?
0
 

Author Comment

by:crazy4s
ID: 34977235
hmm that's actually the output that i get before... the addFile func was initially in the main and now i make it to a func so i need to get back the same output but unfortunately there's no output for it.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34977243
This is what you should type in after the gdb command:

b addFile
r

Now your program should run continuously until addFile is reached.

Now you can enter n or s.

Let me know if this is solves your immediate problem as I'm going away for an hour.

0
 

Author Comment

by:crazy4s
ID: 34977257
?so which line should i supposed to check? i just realized that i don't a count in the addFile func?
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34977273
>> so which line should i supposed to check?

That is easy. You are supposed to thoroughly unit test your code by checking that you reach every line that you wrote in the sequence that you expect, and that the values in each line are exactly as you expect.

This is true for all programs that you write. (At least I am required to not only do that at work, but also to prove that I did that using a special Unit Test methodology that was audited.)

If you don't do that, even if the results today seem to be OK, you could have bad code that will cause something to break even if you add a single line of code that is perfectly valid.

See you in an hour, and then if not done, we'll finish tomorrow.
0
 

Author Comment

by:crazy4s
ID: 34977350
hmm i'm not sure what you want izzit something like tat?
but why there is something are 0 like ActualStruct.pop (run in the first line) but the i and size is increasing everytime runs the while loop?

(gdb) b addFile
Breakpoint 1 at 0x1127c: file sort1.c, line 113.
(gdb) r
Starting program: /home/ugrad/cpfoo/CS224/as2/MY
warning: Temporarily disabling breakpoints for unloaded shared library "/usr/lib/ld.so.1"

Breakpoint 1, addFile (Array2=0x224bc, filename=0x11f58 "AC1.txt", startHere=0) at sort1.c:113
113             int i = startHere;      
(gdb) n
114             int size = startHere;
(gdb) p i
$1 = 0
(gdb) p size
$2 = 0
(gdb) n
119             if((FI = fopen(filename, "r")) == NULL) // open a stream from "countries"
(gdb) p filename
$3 = 0x11f58 "AC1.txt"
(gdb) n
122             if((FO = fopen("DATABASE.txt", "a")) == NULL) // open a stream from "countries"
(gdb) n
125             if((FO2 = fopen("DIRECTORY.txt", "a")) == NULL) // open a stream from "countries"
(gdb) n
128         while ( fgets( (char *) Line,1000,FI) != NULL) // fill buffer up to newline or eof or error
(gdb) n
131             Tok = strtok( Line ,",\n");     // skip ID number
(gdb) n
133             Tok = strtok( NULL ,",\n");     // this should get the country code
(gdb) n
134             ActualStruct.code[0] = Tok[0];
(gdb) n
135             ActualStruct.code[1] = Tok[1];
(gdb) n
136             ActualStruct.code[2] = Tok[2];
(gdb) n
137             ActualStruct.code[3] = 0;       // To create "string"
(gdb) n
139             Tok = strtok( NULL ,",\n");     // this should get the country name
(gdb) n
140             strncpy(&ActualStruct.name[0],Tok,50);  // copy string at most 50 chars
(gdb) p &ActualStruct.name[0]
$4 = 0x26fc0 ""
(gdb) n
142             Tok = strtok( NULL ,",\n");     // skip
(gdb) n
143             Tok = strtok( NULL ,",\n");     // skip
(gdb) n
144             Tok = strtok( NULL ,",\n");     // skip
(gdb) n
145             Tok = strtok( NULL ,",\n");     // skip
(gdb) n
147             Tok = strtok( NULL ,",\n");     // this should get the population
(gdb) n
148             ActualStruct.pop = atoi(Tok);   // convert string to integer
(gdb) p ActualStruct.pop
$5 = 0
(gdb) n
150             Tok = strtok( NULL ,",\n");     // this one should get life expectancy
(gdb) n
151             ActualStruct.life_expectancy = atof(Tok);       // convert string to a floating point number
(gdb) n
153             strcpy(Array2(i).code,ActualStruct.code);       // get the current code
(gdb) n
154             strcpy(Array2(i).name,ActualStruct.name);       // get the current name
(gdb) n
155             Array2(i).pop = ActualStruct.pop;               // get the current population
(gdb) n
156             Array2(i).life_expectancy = ActualStruct.life_expectancy; // get the current life expectancy
(gdb) n
158             strcpy(StructArray(i).code, ActualStruct.code); // get the current code
(gdb) n
159             StructArray(i).offset = ftell(FO);              // get the current offset in the DATABASE file
(gdb) p StructArray(i).offset
$6 = 0
(gdb) n
161             if (fwrite(&Array2(i), sizeof(DATATYPE),1,FO) != 1)  // write the struct to the DATABASE file
(gdb) n
164             i++;
(gdb) p i
$7 = 0
(gdb) n
165             size = i;
(gdb) p size
$8 = 0
(gdb) n
128         while ( fgets( (char *) Line,1000,FI) != NULL) // fill buffer up to newline or eof or error
(gdb) n
131             Tok = strtok( Line ,",\n");     // skip ID number
(gdb) n
133             Tok = strtok( NULL ,",\n");     // this should get the country code
(gdb) n
134             ActualStruct.code[0] = Tok[0];
(gdb) n
135             ActualStruct.code[1] = Tok[1];
(gdb) n
136             ActualStruct.code[2] = Tok[2];
(gdb) n
137             ActualStruct.code[3] = 0;       // To create "string"
(gdb) n
139             Tok = strtok( NULL ,",\n");     // this should get the country name
(gdb) n
140             strncpy(&ActualStruct.name[0],Tok,50);  // copy string at most 50 chars
(gdb) n
142             Tok = strtok( NULL ,",\n");     // skip
(gdb) n
143             Tok = strtok( NULL ,",\n");     // skip
(gdb) n
144             Tok = strtok( NULL ,",\n");     // skip
(gdb) n
145             Tok = strtok( NULL ,",\n");     // skip
(gdb) n
147             Tok = strtok( NULL ,",\n");     // this should get the population
(gdb) n
148             ActualStruct.pop = atoi(Tok);   // convert string to integer
(gdb) n
150             Tok = strtok( NULL ,",\n");     // this one should get life expectancy
(gdb) n
151             ActualStruct.life_expectancy = atof(Tok);       // convert string to a floating point number
(gdb) n
153             strcpy(Array2(i).code,ActualStruct.code);       // get the current code
(gdb) n
154             strcpy(Array2(i).name,ActualStruct.name);       // get the current name
(gdb) n
155             Array2(i).pop = ActualStruct.pop;               // get the current population
(gdb) n
156             Array2(i).life_expectancy = ActualStruct.life_expectancy; // get the current life expectancy
(gdb) n
158             strcpy(StructArray(i).code, ActualStruct.code); // get the current code
(gdb) n
159             StructArray(i).offset = ftell(FO);              // get the current offset in the DATABASE file
(gdb) p StructArray(i).offset
$9 = 0
(gdb) n
161             if (fwrite(&Array2(i), sizeof(DATATYPE),1,FO) != 1)  // write the struct to the DATABASE file
(gdb) n
164             i++;
(gdb) p i
$10 = 1
(gdb) n  
165             size = i;
(gdb) p size
$11 = 1
(gdb)
0
 
LVL 32

Accepted Solution

by:
phoffric earned 500 total points
ID: 34977527
You are running with your latest code post which does not even have addFile in it. So, please post the code you are now running with.

>> but why there is something are 0 like ActualStruct.pop (run in the first line)
Don't know since you didn't p Line so not sure how well the parsing went.

>> but the i and size is increasing everytime runs the while loop?
In you OP are these 2 LOCs:
      i++;  
      size = i;
so that explains why they are increasing.

(1) I wrote:
>> let me know what value of count are your getting everytime you return from addFile.
   What should the value be? What value did you get? Is it correct?

(2) I wrote:
>> Step through the debugger, and when you hit the option 3 (as in your OP), then determine what are the values of the parameters that go into the function you are calling.

Why didn't you post these two results? I can only help if we work together. Otherwise, it will take too long to solve the problem.

To keep debugging simple, just have a file with 2-3 entries so that you don't spend a lot of time looping.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34977555
I'll be leaving shortly.

I see that you are still not using a GUI debugger. Is one available to you? What UNIX version are you using? (And why Unix instead of Linux, just out of curiosity?)
0
 

Author Comment

by:crazy4s
ID: 34979029
no i'm running the latest code with the addFile func in it. i was using the gdb debugger
i'm not sure but the ActualStruct is not copied into the Array2?

cpfoo@csa02 as2$ gcc sort1.c error.c -o MY -g
cpfoo@csa02 as2$ gdb MY
GNU gdb 6.6
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "sparc-sun-solaris2.8"...
(gdb) b addFile
Breakpoint 1 at 0x1127c: file sort1.c, line 113.
(gdb) r
Starting program: /home/ugrad/cpfoo/CS224/as2/MY 
warning: Temporarily disabling breakpoints for unloaded shared library "/usr/lib/ld.so.1"

Breakpoint 1, addFile (Array2=0x224b4, filename=0x11f50 "AC1.txt", startHere=0) at sort1.c:113
113             int i = startHere;      
(gdb) p i
$1 = -12627664
(gdb) n
114             int size = startHere;
(gdb) p size
$2 = 0
(gdb) n
119             if((FI = fopen(filename, "r")) == NULL) // open a stream from "countries"
(gdb) p filename
$3 = 0x11f50 "AC1.txt"
(gdb) n
122             if((FO = fopen("DATABASE.txt", "a")) == NULL) // open a stream from "countries"
(gdb) n
125             if((FO2 = fopen("DIRECTORY.txt", "a")) == NULL) // open a stream from "countries"
(gdb) n
128         while ( fgets( (char *) Line,1000,FI) != NULL) // fill buffer up to newline or eof or error
(gdb) p Line
$4 = "?9(\000\000\000\002\000\000\000\000'", '\0' <repeats 20 times>, "???\000\000\000 \000\000\000\000\000\000\000\000\000?@\000\005?4_??4_?\000\000\000\000\000\000\000d", '\0' <repeats 20 times>, "??E\000\000\000\000\000???\000\n?\030\000\000\000\000\000\000\000\000?9\000\000???\020?4\035\004\000\000\000\000", '?' <repeats 128 times>, "\000\000\000\000\000\000\000\000\000\b", '\0' <repeats 194 times>, "?77\000 \000\000\000??I\020\000\000\000\000\000\000\000\004??{d\000\000\000\024\000\000\000\b\000\000\000\000??@???B?\000\002<???B???I\020?4\0348??"...
(gdb) n
131             Tok = strtok( Line ,",\n");     // skip ID number
(gdb) p Line
$5 = "115,DZA,Algeria,Africa,Northern Africa,2381741,1962,31471000,69.7,49982,Al-Jaza?\210\232?\211?ir/Alg?\210\232àrie,Republic,Abdelaziz Bouteflika,35,DZ\n\000", '?' <repeats 119 times>, "\000\000\000\000\000\000\000\000\000\b", '\0' <repeats 194 times>, "?77\000 \000\000\000??I\020\000\000\000\000\000\000\000\004??{d\000\000\000\024\000\000\000\b\000"...
(gdb) n
133             Tok = strtok( NULL ,",\n");     // this should get the country code 
(gdb) p NULL
No symbol "NULL" in current context.
(gdb) p Tok
$6 = 0xffbff398 "115"
(gdb) n
134             ActualStruct.code[0] = Tok[0];
(gdb) p Tok
$7 = 0xffbff39c "DZA"
(gdb) n
135             ActualStruct.code[1] = Tok[1];
(gdb) n
136             ActualStruct.code[2] = Tok[2];
(gdb) n
137             ActualStruct.code[3] = 0;       // To create "string" 
(gdb) n
139             Tok = strtok( NULL ,",\n");     // this should get the country name 
(gdb) n
140             strncpy(&ActualStruct.name[0],Tok,50);  // copy string at most 50 chars
(gdb) p Tok
$8 = 0xffbff3a0 "Algeria"
(gdb) n
142             Tok = strtok( NULL ,",\n");     // skip
(gdb) n
143             Tok = strtok( NULL ,",\n");     // skip 
(gdb) n
144             Tok = strtok( NULL ,",\n");     // skip
(gdb) n
145             Tok = strtok( NULL ,",\n");     // skip 
(gdb) n
147             Tok = strtok( NULL ,",\n");     // this should get the population
(gdb) n
148             ActualStruct.pop = atoi(Tok);   // convert string to integer
(gdb) p Tok
$9 = 0xffbff3cc "31471000"
(gdb) n
150             Tok = strtok( NULL ,",\n");     // this one should get life expectancy
(gdb) n
151             ActualStruct.life_expectancy = atof(Tok);       // convert string to a floating point number
(gdb) p Tok
$10 = 0xffbff3d5 "69.7"
(gdb) n
153             strcpy(Array2[i].code,ActualStruct.code);       // get the current code 
(gdb) p Array2[i].code
$11 = "\000\000\000"
(gdb) p ActualStruct.code
$12 = "DZA"
(gdb) n
154             strcpy(Array2[i].name,ActualStruct.name);       // get the current name
(gdb) p Array2[i].name
$13 = '\0' <repeats 49 times>
(gdb) p ActualStruct.name
$14 = "Algeria", '\0' <repeats 42 times>
(gdb) n
155             Array2[i].pop = ActualStruct.pop;               // get the current population
(gdb) p Array2[i].pop
$15 = 0
(gdb) p ActualStruct.pop
$16 = 31471000
(gdb) p Array2[0].pop
$17 = 0
(gdb) n
156             Array2[i].life_expectancy = ActualStruct.life_expectancy; // get the current life expectancy
(gdb) p Array2[1].life_expectancy
$18 = 0
(gdb) p ActualStruct.life_expectancy
$19 = 69.6999969
(gdb) n 
158             strcpy(StructArray[i].code, ActualStruct.code); // get the current code 
(gdb) p StructArray[i].code
$20 = "\000\000\000"
(gdb) p ActualStruct.code
$21 = "DZA"
(gdb) n
159             StructArray[i].offset = ftell(FO);              // get the current offset in the DATABASE file 
(gdb) p ftell(FO)
$22 = 896
(gdb) p StructArray[i].offset
$23 = 0
(gdb) n
161             if (fwrite(&Array2[i], sizeof(DATATYPE),1,FO) != 1)  // write the struct to the DATABASE file 
(gdb) p &Array2[i]
$24 = (DATATYPE *) 0x224b4
(gdb) p 0x224b4
$25 = 140468
(gdb) n
164             i++;
(gdb) p i
$26 = 0
(gdb) n
165             size = i;
(gdb) p size
$27 = 0
(gdb) n
128         while ( fgets( (char *) Line,1000,FI) != NULL) // fill buffer up to newline or eof or error
(gdb) p Line
$28 = "115\000DZA\000Algeria\000Africa\000Northern Africa\0002381741\0001962\00031471000\00069.7\00049982,Al-Jaza?\210\232?\211?ir/Alg?\210\232àrie,Republic,Abdelaziz Bouteflika,35,DZ\n\000", '?' <repeats 119 times>, "\000\000\000\000\000\000\000\000\000\b", '\0' <repeats 194 times>, "?77\000 \000\000\000??I\020\000\000\000\000\000\000\000\004??{d\000\000\000\024\000\000\000\b\000"...
(gdb) n
131             Tok = strtok( Line ,",\n");     // skip ID number
(gdb) p Line
$29 = "146,AGO,Angola,Africa,Central Africa,1246700,1975,12878000,38.3,6648,Angola,Republic,Jos?\210\232à Eduardo dos Santos,56,AO\n\000outeflika,35,DZ\n\000", '?' <repeats 119 times>, "\000\000\000\000\000\000\000\000\000\b", '\0' <repeats 194 times>, "?77\000 \000\000\000??I\020\000\000\000\000\000\000\000\004??{d\000\000\000\024\000\000\000\b\000"...
(gdb) n
133             Tok = strtok( NULL ,",\n");     // this should get the country code 
(gdb) n
134             ActualStruct.code[0] = Tok[0];
(gdb) p Tok
$30 = 0xffbff39c "AGO"

Open in new window

0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

Author Comment

by:crazy4s
ID: 34979041
this is my latest code
#include	<stdio.h>
#include 	<string.h>
#include 	<stdlib.h>
#include 	"ourhdr.h"

typedef struct				// Country Data struct declaration
    	{  	
		char code[4]; 		// Country Code 
       		char name[50];		// Country Name
		float life_expectancy;	// Life Expentancy of the Country's citizen
		int pop;		// Country's Population
    	} DATATYPE;

typedef struct				// Index Data struct declaration
	{
		char code[4];		
		long int offset;	// offset of the data
	} INDEX;

INDEX StructArray[300];	// for a lot of them
DATATYPE ActualStruct; // for a single struct
DATATYPE DatabaseArray[300]; 	// DATATYPE array

/****************************Add File***********************************************/

int addFile(DATATYPE* Array2, char* filename, int startHere)
{
	int i = startHere;	
	int size = startHere;
	char * Tok;         // token from line
	FILE *FI, *FO, *FO2;
	char Line[1000];  // NO input line (delimited by \n) is longer than 1000

	if((FI = fopen(filename, "r")) == NULL) // open a stream from "countries"
    		err_sys("Open Fail\n");

	if((FO = fopen("DATABASE.txt", "a")) == NULL) // open a stream from "countries"
    		err_sys("Open DATABASE Fail\n");

	if((FO2 = fopen("DIRECTORY.txt", "a")) == NULL) // open a stream from "countries"
    		err_sys("Open DIRECTORY Fail\n");

    while ( fgets( (char *) Line,1000,FI) != NULL) // fill buffer up to newline or eof or error
    {

	Tok = strtok( Line ,",\n"); 	// skip ID number

        Tok = strtok( NULL ,",\n"); 	// this should get the country code 
        ActualStruct.code[0] = Tok[0];
        ActualStruct.code[1] = Tok[1];
        ActualStruct.code[2] = Tok[2];
        ActualStruct.code[3] = 0; 	// To create "string" 

	Tok = strtok( NULL ,",\n"); 	// this should get the country name 
        strncpy(&ActualStruct.name[0],Tok,50);	// copy string at most 50 chars

	Tok = strtok( NULL ,",\n"); 	// skip
	Tok = strtok( NULL ,",\n"); 	// skip 
	Tok = strtok( NULL ,",\n"); 	// skip
	Tok = strtok( NULL ,",\n"); 	// skip 

	Tok = strtok( NULL ,",\n"); 	// this should get the population
	ActualStruct.pop = atoi(Tok);	// convert string to integer

        Tok = strtok( NULL ,",\n"); 	// this one should get life expectancy
        ActualStruct.life_expectancy = atof(Tok);	// convert string to a floating point number

	strcpy(Array2[i].code,ActualStruct.code);	// get the current code 
	strcpy(Array2[i].name,ActualStruct.name);	// get the current name
	Array2[i].pop = ActualStruct.pop;		// get the current population
	Array2[i].life_expectancy = ActualStruct.life_expectancy; // get the current life expectancy

	strcpy(StructArray[i].code, ActualStruct.code);	// get the current code 
	StructArray[i].offset = ftell(FO);             	// get the current offset in the DATABASE file 

	if (fwrite(&Array2[i], sizeof(DATATYPE),1,FO) != 1)  // write the struct to the DATABASE file 
		err_sys("fwrite error");

	i++;
	size = i;
	}

/****************************Sort the array and write into DIRECTORY*****************************/

	sort(StructArray,size);	// call sort function
	
	for (i=0; i<size; i++)
	{	
		if (fwrite(&StructArray[i], sizeof(INDEX),1,FO2) != 1)  // write the struct to the DIRECTORY file 
			err_sys("fwrite error");
	}

	if (fclose(FI))				// close file descriptor FI
		err_sys("Close error\n");	
	if (fclose(FO))				// close file descriptor FO
		err_sys("Close error\n");	
	if (fclose(FO2))			// close file descriptor FO2
		err_sys("Close error\n");

	return i;

}
/****************************************Main Function********************************************/

int main() 
{ 
  	char userfile[50];
  	int count = 0;
	int size = 0;
	count = addFile(DatabaseArray,"AC1.txt",0);
	
/*********************************************MENU************************************************/

	int c = -1;
	while( c != 4)
	{
		printf("Please select an option (1 to 4):\n");
		printf("1. Add to the DATABASE\n");
		printf("2. Search the DATABASE\n");
		printf("3. List all the countries in DATABASE by ordered Country Code\n");
		printf("4. Press q to exit\n");
		fflush(stdin);
		c = -1;		// error value if scanf fails
		scanf("%d", &c);
		switch (c)
		{
			case 1:
                                printf("Filename(data that you would like to add in): ");
				scanf("%s",&userfile);
				count = addFile(DatabaseArray, userfile, count);
				break;
			case 2:
				search(size);
				break;
			case 3: 
				printsort(size);
				break;
			case 4:
				puts("Exiting program!");
				return 0;
			default:
				printf("\nNot implemented yet!");
		}
	}
}

Open in new window

0
 
LVL 32

Expert Comment

by:phoffric
ID: 34983439
To remain focussed on your OP question, you will still need to address these questions (3rd time repeating):
>> let me know what value of count are your getting everytime you return from addFile.
>>    What should the value be? What value did you get? Is it correct?

Using your latest code post, then at line 110:
        count = addFile(DatabaseArray,"AC1.txt",0);
is the value of count what you require?

>> when you hit the option 3 (as in your OP), then determine what are the values of the parameters that go into the function you are calling.

Using your latest code post, then at line 136:
        printsort(size);
is the value of size what you require?

I see that you have some parsing questions as a result of using the debugger. That is good that your whitebox testing is raising new questions. After you achieve the goal in your OP question, you can ask more questions if the program is not working properly.
0
 

Author Comment

by:crazy4s
ID: 34985515
hmm let me clarify something this the count code was actually given by one of the expert in my previous post and i would like to know what're the codes are too but he didn't give me any reply so i couldn't find an ans too and so i open a new question here?
ok back to your question... so now u want to me check what is the count is in the main func ryte?
hmm i got 7 for the count for this line >>      count = addFile(DatabaseArray,"AC1.txt",0);

(gdb) b main
Breakpoint 1 at 0x1177c: file sort1.c, line 193.
(gdb) r
Starting program: /home/ugrad/cpfoo/CS224/as2/MY 
warning: Temporarily disabling breakpoints for unloaded shared library "/usr/lib/ld.so.1"

Breakpoint 1, main () at sort1.c:193
193             int count = 0;
(gdb) p count
$1 = 0
(gdb) n
194             int size = 0;
(gdb) p size
$2 = 0
(gdb) n
195             count = addFile(DatabaseArray,"AC1.txt",0);
(gdb) 
203             if((infile = fopen("DIRECTORY.txt", "rb")) == NULL) // open a stream from "countries"
(gdb) p count
$3 = 7

Open in new window


hmm i really sorry but because i didn't get any reply for 2 days in the previous post...so i got no idea what the code is.... and i really wanted to understand it!

>> when you hit the option 3 (as in your OP), then determine what are the values of the parameters that go into the function you are calling.

Using your latest code post, then at line 136:
        printsort(size);
is the value of size what you require?

hmm i don't really know how to check this, can you lead me?
thanks for the understanding:)
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34986329
good news..
   Your question is that you got no output; and to get the output that I posted, you will only need to make very minor changes.


I noticed that your last code post is missing some functions, but that's ok, since your debug results are useful.

>> i don't really know how to check this, can you lead me?
    Before the printsort(size); statement, you just print out the value of size. You don't have to show me the entire output, just the value of size. Since you haven't read the gdb link I gave you, you can forget gdb (or preferably ddd), and just add debug print statements to figure everything out.


>> hmm i got 7 for the count for this line >>      count = addFile(DatabaseArray,"AC1.txt",0);
>> the count code was actually given by one of the expert in my previous post and i would like to know what're the codes are
    In a program, every variable has a meaning, right? You are the designer and programmer of this code, so the meaning is up to you to clearly define. You got a number 7 for count. You are going to have to post what the definition of count is. Likewise, you are going to have to post what the definition of size is.

    Once you understand these two definitions, then you will be able to know whether the values you are seeing are correct or not. It is important that you figure this out by either code inspection and/or by debugging techniques that you are using.

>> but he didn't give me any reply ..
   You should not have closed the question if you didn't understand the advice given. I see that you hit the RA button which would given you more assistance; but then you closed the question, so the RA became obsolete. At this point, you have some code which is at least at the intermediate C++ level. But your questions here are still representative of the beginning level. You must take a step back and relearn the basics thoroughly understanding the exercises starting with a blank project, before trying to move onto more complex projects.

   At this point, I have no idea how much of the code is yours (meaning you understand precisely what is going on) and how much belongs to the experts who basically wrote some of the code for you without you taking ownership of the code.
0
 

Author Comment

by:crazy4s
ID: 34987561
i understand part of it but i need more details about it and yes i'm still at the beginner stage !
well for the printsort(size) , i'm not sure is it correct to check it like that?
but i got 0 for the size?

(gdb) b printsort
Breakpoint 1 at 0x10e4c: file sort1.c, line 57.
(gdb) r
Starting program: /home/ugrad/cpfoo/CS224/as2/MY 
warning: Temporarily disabling breakpoints for unloaded shared library "/usr/lib/ld.so.1"
Please select an option (1 to 4):
1. Add to the DATABASE
2. Search the DATABASE
3. List all the countries in DATABASE by ordered Country Code
4. Press q to exit
3

Breakpoint 1, printsort (size=0) at sort1.c:57
57              sort(StructArray,size); // call sort function
(gdb) n
59              if((FI = fopen("DATABASE.txt", "r")) == NULL) // open DATABASE for read
(gdb) p size
$1 = 0

Open in new window

0
 

Author Comment

by:crazy4s
ID: 34987581
well i'm not sure where has gone wrong as i check in the addFile fun after the while loop the i = size is 7 and everything seems to be fine but when come the printsort func the size became 0 and i don't really understand why?
0
 
LVL 32

Assisted Solution

by:phoffric
phoffric earned 500 total points
ID: 34987657
Here are two variables abc defined in two functions, fun1 and fun2. Did you know that even though they have the same name, they are different variables?
int fun1() {
   int abc;
...
}

int fun2() {
   int abc;
...
}

Open in new window

0
 

Author Comment

by:crazy4s
ID: 34987686
so did u meant that because i've already use int size in other place and i used back int size again in printsort(size) that's why is a different int size from the search(size)? both size are having different value?
0
 

Author Comment

by:crazy4s
ID: 34987717
do you meant like that?
/*************************Print Sorted Array**********************************************/
void printsort(int k)
{
        DATATYPE country;

	sort(StructArray,k);	// call sort function
	FILE *FI;
	if((FI = fopen("DATABASE.txt", "r")) == NULL) // open DATABASE for read
    		err_sys("Open DATABASE Fail\n");
	int i;
	printf("--------------------------------------------------------------------------------------------------------\n");
	printf("  CODE \t\t\t COUNTRY NAME \t\t\t   POPULATION      LIFE EXPECTANCY \t OFFSET\n");
	printf("--------------------------------------------------------------------------------------------------------\n");
	
	for (i=0; i<k; i++)
	{	
              	fseek(FI,StructArray(i).offset,SEEK_SET);	//seek the offset in the binary file
               	fread(&country, sizeof(DATATYPE),1,FI);	// read the struct of array from binary file (4 fields)
		printf("%5s%50s%15u%18f%15u\n", country.code, country.name, country.pop, country.life_expectancy, StructArray[i].offset);
	}
} 

/************************Search Function by Country Code*********************************/
void search(int size)
{
	int mid, lower = 0, upper = size, flag = 1;
	INDEX cc;
	FILE *FI;
	if((FI = fopen("DATABASE.txt", "r")) == NULL) // open DATABASE for read
    		err_sys("Open DATABASE Fail\n");
	printf("Enter Country Code to search: ");
	scanf("%s", &cc);

	for(mid = (lower+upper)/2; lower <= upper; mid = (lower + upper)/2)
	{
		if(strcmp(StructArray[mid].code, cc.code) == 0)		// compare the input with the sorted array
		{
			printf("The country code is at position %d in the array at offset %u in the binary file.\n", mid, StructArray[mid].offset);
                        fseek(FI,StructArray[mid].offset,SEEK_CUR);	//seek the offset in the binary file
                        fread(&DatabaseArray[mid], sizeof(DATATYPE),1,FI);	// read the struct of array from binary file (4 fields)
			printf("%s %s %u %f\n", DatabaseArray[mid].code, DatabaseArray[mid].name, DatabaseArray[mid].pop, DatabaseArray[mid].life_expectancy);
			flag = 0;
			break;
		}
		if(strcmp(StructArray[mid].code, cc.code) > 0)		// compare the input with the sorted array
			upper = mid - 1;
		else
			lower = mid + 1;
	}
	
	if (flag)
		printf("Elements not found.");				// print this if the input is not in the array	

	if (fclose(FI))				// close file descriptor FI
		err_sys("Close error\n");
}

/****************************Add File***********************************************/

int addFile(DATATYPE* Array2, char* filename, int startHere)
{
	int i = startHere;	
	int size = startHere;
	int k = startHere;
	char * Tok;         // token from line
	FILE *FI, *FO, *FO2;
	char Line[1000];  // NO input line (delimited by \n) is longer than 1000

	if((FI = fopen(filename, "r")) == NULL) // open a stream from "countries"
    		err_sys("Open Fail\n");

	if((FO = fopen("DATABASE.txt", "a")) == NULL) // open a stream from "countries"
    		err_sys("Open DATABASE Fail\n");

	if((FO2 = fopen("DIRECTORY.txt", "a")) == NULL) // open a stream from "countries"
    		err_sys("Open DIRECTORY Fail\n");

    while ( fgets( (char *) Line,1000,FI) != NULL) // fill buffer up to newline or eof or error
    {

	Tok = strtok( Line ,",\n"); 	// skip ID number

        Tok = strtok( NULL ,",\n"); 	// this should get the country code 
        ActualStruct.code[0] = Tok[0];
        ActualStruct.code[1] = Tok[1];
        ActualStruct.code[2] = Tok[2];
        ActualStruct.code[3] = 0; 	// To create "string" 

	Tok = strtok( NULL ,",\n"); 	// this should get the country name 
        strncpy(&ActualStruct.name[0],Tok,50);	// copy string at most 50 chars

	Tok = strtok( NULL ,",\n"); 	// skip
	Tok = strtok( NULL ,",\n"); 	// skip 
	Tok = strtok( NULL ,",\n"); 	// skip
	Tok = strtok( NULL ,",\n"); 	// skip 

	Tok = strtok( NULL ,",\n"); 	// this should get the population
	ActualStruct.pop = atoi(Tok);	// convert string to integer

        Tok = strtok( NULL ,",\n"); 	// this one should get life expectancy
        ActualStruct.life_expectancy = atof(Tok);	// convert string to a floating point number

	strcpy(Array2(i).code,ActualStruct.code);	// get the current code 
	strcpy(Array2(i).name,ActualStruct.name);	// get the current name
	Array2(i).pop = ActualStruct.pop;		// get the current population
	Array2(i).life_expectancy = ActualStruct.life_expectancy; // get the current life expectancy

	strcpy(StructArray(i).code, ActualStruct.code);	// get the current code 
	StructArray(i).offset = ftell(FO);             	// get the current offset in the DATABASE file 

	if (fwrite(&Array2(i), sizeof(DATATYPE),1,FO) != 1)  // write the struct to the DATABASE file 
		err_sys("fwrite error");

	i++;
	size = i;
	k = size;
	}

/****************************Sort the array and write into DIRECTORY*****************************/

	sort(StructArray,size);	// call sort function
	
	for (i=0; i<size; i++)
	{	
		if (fwrite(&StructArray(i), sizeof(INDEX),1,FO2) != 1)  // write the struct to the DIRECTORY file 
			err_sys("fwrite error");
	}

	if (fclose(FI))				// close file descriptor FI
		err_sys("Close error\n");	
	if (fclose(FO))				// close file descriptor FO
		err_sys("Close error\n");	
	if (fclose(FO2))			// close file descriptor FO2
		err_sys("Close error\n");

	return i;

}
/****************************************Main Function********************************************/

int main() 
{ 
  	char userfile[50];
  	int count = 0;
	int size = 0;
	int k = 0;
	count = addFile(DatabaseArray,"AC1.txt",0);
	
/*********************************************MENU************************************************/

	int c = -1;
	while( c != 4)
	{
		printf("Please select an option (1 to 4):\n");
		printf("1. Add to the DATABASE\n");
		printf("2. Search the DATABASE\n");
		printf("3. List all the countries in DATABASE by ordered Country Code\n");
		printf("4. Press q to exit\n");
		fflush(stdin);
		c = -1;		// error value if scanf fails
		scanf("%d", &c);
		switch (c)
		{
			case 1:
                                printf("Filename(data that you would like to add in): ");
				scanf("%s",&userfile);
				count = addFile(DatabaseArray, userfile, count);
				break;
			case 2:
				search(size);
				break;
			case 3: 
				printsort(k);
				break;
			case 4:
				puts("Exit program!");
				return 0;
			default:
				printf("\nNot implemented yet!");
		}
	}
}

Open in new window

0
 
LVL 32

Expert Comment

by:phoffric
ID: 34987791
>> so did u meant that because i've already use int size in other place and i used back int size again in printsort(size) that's why is a different int size from the search(size)? both size are having different value?
    The "size" variable in main is not the same as the size variable in addFile. You can keep the names the same, if you want (although I do like the idea of them being different), but you should realize that they are defined on the function's respective stacks at different memory locations.

You posted new code. Please always test code before posting. I doubt your new code solves the problem; but you need to determine that ahead of time and figure out what is wrong (as you have been doing in previous posts).

I see you have this line:
    printsort(k);    <<---- so, you changed the "size" to "k"
But, you didn't tell me what value "k" should be when you hit this line. What is the definition of your "k"?

At work (and I hope, at school), we write code like this:
    int speed;   // the speed (mph) of the train

Open in new window

So, I advise you to fully comment your code explaining the definition of the variables and blocks of code. These comments will represent your design.
0
 

Author Comment

by:crazy4s
ID: 34987828
well it should be equal to size means 7 but when i check through gdb is still 0:(
0
 

Author Comment

by:crazy4s
ID: 34987843
as i put this at the at end of the while loop in the addFile func
      i++;
      size = i;
      k = size;
hmm yeah i forgot to put it as i was in a hurry to finish up everything..
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34987892
It looks like adding k is just redundant with size. That is, they have identical meaning. I could say more about some redundancies, but I'll leave that to you.

When you set k = size in addFile, you now understand that this k is not the same k that you defined in main. So setting k to size in addFile doesn't get the k in main to be set to that value using this approach. The k's are different variables.
0
 

Author Comment

by:crazy4s
ID: 34987937
hmm not really get it.... why size can but not k?
0
 

Author Comment

by:crazy4s
ID: 34988035
i just found out even the size in the search func is also 0...
because when i tried to search by cc the list only have the first data of the sorted data which is AGO while others are not found?
this means the no of size and k is not being bring into the main func so what should i do now?
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34988055
>> why size can but not k?
no, neither can.

size defined in addFile is a different variable than size defined in main.
  k   defined in addFile is a different variable than   k    defined in main.

So if you set size in addFile to some value, then the value of size in main has not changed because of that. Same thing is true for k.

You agree, that if you set a variable to some value, you should use it somewhere (otherwise, why bother setting it). So, in addFile, when you set the local variable, k, to some value, where are you using it. Maybe you thought you were using it in main, but now you know that the k in main is not the same variable as in addFile.

So, where are you using the k in addFile?


0
 

Author Comment

by:crazy4s
ID: 34988069
ok i've solved the prob!XD
i put smt like this in the main after the      count = addFile(DatabaseArray,"AC1.txt",0);
      size = count;
      k = count;
but when i add a new file, the new file is not added in, where is the prob?

Please select an option (1 to 4):
1. Add to the DATABASE
2. Search the DATABASE
3. List all the countries in DATABASE by ordered Country Code
4. Press q to exit
3
--------------------------------------------------------------------------------------------------------
  CODE                   COUNTRY NAME                      POPULATION      LIFE EXPECTANCY       OFFSET
--------------------------------------------------------------------------------------------------------
  AGO                                            Angola       12878000         38.299999             64
  BDI                                           Burundi        6695000         46.200001            384
  BEN                                             Benin        6097000         50.200001            128
  BFA                                      Burkina Faso       11937000         46.700001            320
  BWA                                          Botswana        1622000         39.299999            192
  DZA                                           Algeria       31471000         69.699997              0
  IOT                    British Indian Ocean Territory              0          0.000000            256
Please select an option (1 to 4):
1. Add to the DATABASE
2. Search the DATABASE
3. List all the countries in DATABASE by ordered Country Code
4. Press q to exit
2
Enter Country Code to search: BEN
The country code is at position 2 in the array at offset 128 in the binary file.
BEN Benin 6097000 50.200001
Please select an option (1 to 4):
1. Add to the DATABASE
2. Search the DATABASE
3. List all the countries in DATABASE by ordered Country Code
4. Press q to exit
1
Filename(data that you would like to add in): A.txt
Please select an option (1 to 4):
1. Add to the DATABASE
2. Search the DATABASE
3. List all the countries in DATABASE by ordered Country Code
4. Press q to exit
3
--------------------------------------------------------------------------------------------------------
  CODE                   COUNTRY NAME                      POPULATION      LIFE EXPECTANCY       OFFSET
--------------------------------------------------------------------------------------------------------
  AGO                                            Angola       12878000         38.299999             64
  BDI                                           Burundi        6695000         46.200001            384
  BEN                                             Benin        6097000         50.200001            128
  BFA                                      Burkina Faso       11937000         46.700001            320
  BWA                                          Botswana        1622000         39.299999            192
  DZA                                           Algeria       31471000         69.699997              0
  IOT                    British Indian Ocean Territory              0          0.000000            256

0
 

Author Comment

by:crazy4s
ID: 34988138
woot! I've solved all the problems i just need to defined one more time for size and k in the option 1!!!!
Thanks for all the help yaXD
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34988173
I'm glad YOU solved the problem, and not me. :)

Here's a refinement. Take a look again at main now that you have the output.
Put a comment in for the definition of count, size, and k. What do you find? Are there any redundancies. The more redundancies you have, the more likely you will introduce bugs. Do you really need all three variables (count, size, and k) in main?

Try experimenting on your own to see if you can remove redundant variables and still get the correct answer.
0
 

Author Comment

by:crazy4s
ID: 34988182
hmm wait it was fine when i tried it with a small data but when come to a big file it runs smoothly for option 2 and 3 but when i wanted to add a new file and hit the enter button it gives me a segmentation fault

Filename(data that you would like to add in): AllCountries2.txt

Program received signal SIGSEGV, Segmentation fault.
0xff2c13d0 in atoi () from /usr/lib/libc.so.1

what is this meant?
sorry to bother you once again~
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34988215
In a complex project, there are always more than one problem, and each problem is worthy of another question. Before you ask the question, try using the techniques you have learned (such as stepping through the program one line at a time) and seeing where gdb complains. Now you will know the LOC it faults on. Then print out some variables that are on that line and the preceeing line. This should lead you to some clues as to what is wrong.

You may have to start the run over again several times to collect information (depending on what is causing the problem). It could be some earlier variable is set incorrectly (or not set) and there is a cascading effect resulting in a program crash.

Try to collect as many clues as possible. Then, if you are still stuck, hit the related question button, post all your code, identify the LOC where it crashes, and give out as many variables values near the crash as you think are relevant.

I'll be back tomorrow to see how you are doing. (Maybe tonight briefly.)
0
 

Author Comment

by:crazy4s
ID: 34988499
thanks i've already figured out the error!
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34988507
Super!! Now get yourself a GUI debugger and save yourself a lot of grief.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
The greatest common divisor (gcd) of two positive integers is their largest common divisor. Let's consider two numbers 12 and 20. The divisors of 12 are 1, 2, 3, 4, 6, 12 The divisors of 20 are 1, 2, 4, 5, 10 20 The highest number among the c…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now