I have created a program which takes as an input:
a number which determines the shape the user wants to be printed,lets say copies
a number which the determines the 'size' of the shape
and a number which determines how many times the shape will be printed..
What I have tried is a for loop in main() function below each 'if' but the copies are printed one down another..I also came up with the idea of printing the first line <'copies'> times with the necessary padding but that practice seems to be different for every shape (and yes I cannot implement this logic in my code)...What can I do?
/*
Version 5*/
#include <stdio.h>
#include <stdio.h>
int getchoice(void);
int getsize(void);
void oof(int size,int copies);
void printrhombus(int size);
void printrighttriangle(int size);
void printisoscelestriangle(int size);
void printspace(void);
void printsymbol(void);
void printnewline(void);
void printrowno(int i);
int getcopies(void);
int main(void)
{
int choice = 0;
int size;
int copies;
for(; (choice = getchoice()) != -1 ;)
{
size = getsize();
copies = getcopies();
if(choice == 0)
{
oof(size,copies);
}
else if(choice == 1)
{
printrhombus(size);
}
else if(choice == 2)
{
printrighttriangle(size);
}
else if (choice == 3)
{
printisoscelestriangle(size);
}
}
return 0;
}
int getchoice(void)
{
int choice;
printf("Please enter which shape you want to be printed (0-3):\n");
scanf("%d",&choice);
printf("Your choice is %d\n",choice);
return choice;
}
int getsize(void)
{
int size;
printf("Please enter the number of rows-the size of your shape:\n");
scanf("\n%d",&size);
printf("Your size is %d\n",size);
return size;
}
void oof(int size,int copies)
{
int i,j,k,l;
for(i = 0; i< size; i++)
{
for(l = 0; l<copies; l++)
{
for(j = 0;j<i;j++)
{
printsymbol();
}
}
for(k =0;k<size;k++)
{
if(k == 0 || i == 0 || k == size-1 || i == size-1)
{
printrowno(i);
}
else printsymbol();
}
printnewline();
}
}
void printrhombus(int size)
{
int i,j;
int rows1 = (size/2)+1;
for(i = 1;i<=rows1;i++)
{
for(j = 1;j<=((2*rows1)-1);j++)
{
if((j==(rows1+(i-1))) || j==(rows1-(i-1)))
{
printrowno(i);
}
else if(j>rows1+i-1)
{
printspace();
}
else if(j<rows1+i-1 && j!= rows1+1-i)
{
printsymbol();
}
}
printnewline();
}
for(i = rows1-1;i>=1;i--)
{
for(j=1;j<=((2*rows1)-1);j++)
{
if((j==(rows1+(i-1))) || j==(rows1-(i-1)))
{
printrowno(size-i+1);
}
else if(j>rows1+i-1)
{
printspace();
}
else if(j<rows1+i-1 && j!= (rows1+1-i))
{
printsymbol();
}
}
printnewline();
}
}
void printrighttriangle(int size)
{
int rowno,colno;
for(rowno = 1; rowno<=size; rowno++)
{
for(colno = 1; colno<= rowno; colno++)
{
if ((colno==1) || (rowno == size) || colno == rowno)
{
printrowno(rowno);
}
else if(colno>rowno)
{
printspace();
}
else
{
printsymbol();
}
}
printnewline();
}
}
void printisoscelestriangle(int size)
{
int i,j;
for(i = 1; i<= size; i++)
{
for(j = 1;j<= ((2*size)-1);j++)
{
if(j ==(size-(i-1)) ||j == (size+(i-1))|| i == size)
{
printrowno(i);
}
if (j<size-(i-1))
{
printspace();
}
if(j>(size-(i-1)) && j<(size +(i-1))&& i!= size)
{
printsymbol();
}
}
printnewline();
}
}
void printspace(void)
{
printf(" ");
return;
}
void printsymbol(void)
{
printf("-");
return;
}
void printrowno(int i)
{
printf("%d",i);
}
void printnewline(void)
{
printf("\n");
return;
}
int getcopies(void)
{
int copies;
printf("Please enter number of copies:\n");
scanf("\n%d",&copies);
return copies;
}
I'm new on the subject of data structures so forgive me if Im asking a stupid question, I've been trying to figure this out myself but got nowhere.
These are the functions I'm working on and I think I initialized the file properly. However I couldn't understand why the function GetString prints an infinite loop of spaces. I have another function that exported some data on the said file. When i deleted the ImportListOfCompanyData function everything seems in order and the file is exported as it should be. However when ImportListOfCompanyData is there, the file is NULL.
void char * GetString(FILE *fp)
{
char c;
while(c != '\n')
{
c = fgetc(fp);
printf("%c", c);
}
}
void ImportListOfCompanyData(char *FileName, struct CompanyType s[], int maxit1, int maxit2)
{
FILE * fp;
char c;
fp = fopen(FileName, "r");
if (fp==NULL)
{
printf("Error creating the file \n");
exit(1);
}
GetString(fp);
fclose(fp);
}
Someone asked for the complete code: It's bit long sorry!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXNUM 100
struct Department
{
char DepName[MAXNUM];
int NuEmp;
double Budget;
int dflag;
};
typedef struct Department DEP;
struct CompanyType
{
char CompName[MAXNUM];
char OwnerName[MAXNUM];
int Year;
double StockPrice;
int flag;
DEP Dep[MAXNUM];
};
struct ImpDepartment
{
char IDepName[MAXNUM];
int INuEmp;
double IBudget;
int Idflag;
};
typedef struct ImpDepartment IDEP;
struct ImpCompanyType
{
char ICompName[MAXNUM];
char IOwnerName[MAXNUM];
int IYear;
double IStockPrice;
int Iflag;
IDEP IDep[MAXNUM];
};
void CreateCompany(struct CompanyType s[], char * cname, char * cowner, int year, double sprice, int i)
{
strcpy(s[i].CompName, cname);
strcpy(s[i].OwnerName, cowner);
s[i].Year = year;
s[i].StockPrice = sprice;
s[i].flag = 0;
}
int PrintCompany(struct CompanyType s[], int maxit1, int maxit2)
{
int flag = 0, i = 0;
while(i <= maxit1)
{
if(s[i].flag == 1)
{
flag = 1;
break;
}
printf("%d. Company %s: \n\n", i + 1, s[i].CompName);
printf("****************\n");
printf("Owned by: %s\n", s[i].OwnerName);
printf("Establishment year: %d\n", s[i].Year);
printf("Stock price: %.2lf\n", s[i].StockPrice);
printf("****************\n\n");
int j = 0;
while(j < maxit2)
{
if(s[i].Dep[j].dflag == 1)
{
flag = 1;
break;
}
printf("****************\n");
printf("%d. Department %s: \n", j + 1, s[i].Dep[j].DepName);
printf("Number of employees: %d\n", s[i].Dep[j].NuEmp);
printf("Budget: %.2lf\n", s[i].Dep[j].Budget);
printf("****************\n\n");
j++;
}
i++;
}
if(flag == 1)
return -1;
else
return 0;
}
int CompareName(char * str1, char * str2)
{
char *stra, *strb;
int result;
result = strcmp(str2, str1);
return result;
}
void DeleteCompany(struct CompanyType s[], char * cname, int n)
{
int i = 0, check = 0;
while(i <= n)
{
if(CompareName(s[i].CompName, cname)== 0)
{
check = 1;
break;
}
i++;
}
if(check == 1)
{
s[i].flag = 1;
printf("Company %s was successfully deleted!\n", s[i].CompName);
}
else
printf("The input is wrong!");
}
void UnDeleteCompany(struct CompanyType s[], char * cname, int n)
{
int i = 0, check = 0;
while(i <= n)
{
if(CompareName(s[i].CompName, cname)== 0)
{
check = 1;
break;
}
i++;
}
if(check == 1)
{
if(s[i].flag == 0)
{
printf("The Company %s wasn't deleted in the first place.\n\n", s[i].CompName);
}
else
{
s[i].flag = 0;
printf("Company %s was successfully undeleted!\n\n", s[i].CompName);
}
}
else
printf("The input is wrong!");
}
int SearchForCompany(struct CompanyType s[], char * cname, int maxit, int a)
{
int i = 0;
int check = 0;
int m = 0;
while(i <= maxit)
{
if(CompareName(s[i].CompName, cname)== 0)
{
check = 1;
break;
}
i++;
}
if(check == 1)
{
if(s[i].flag == 1)
{
printf("The company ""%s"" doesn't exist\n\n", cname);
}
else
{
if(a == 1)
{
printf("The company %s was found!", s[i].CompName, s[i].CompName);
m = 1;
}
else
m = 1;
}
}
else
printf("The company ""%s"" doesn't exist\n\n", cname);
if (m == 1)
return i;
else
return -1;
}
void AddDeparments(struct CompanyType s[], char * cname, int maxit, int a, char * dname, int nem, double bud, int depno)
{
int n;
n = SearchForCompany(s,cname, maxit, a);
if(maxit == -1)
return -1;
strcpy(s[n].Dep[depno].DepName, dname);
s[n].Dep[depno].NuEmp = nem;
s[n].Dep[depno].Budget = bud;
s[n].Dep[depno].dflag = 0;
printf("The department %s was created in the %s company\n",s[n].Dep[depno].DepName, s[n].CompName);
}
int SearchForDepartments(struct CompanyType s[], char * dname, int maxit1, int maxit2, int a, int *succ, int *i, int*j)
{
int check = 0;
while((*j) <= maxit1)
{
while((*i) <= maxit2)
{
if(CompareName(s[(*i)].Dep[(*j)].DepName, dname)== 0)
{
check = 1;
break;
}
(*i)++;
}
if(check == 1)
break;
(*j)++;
}
if(check == 1)
{
if(s[(*i)].Dep[(*j)].dflag == 1)
{
printf("The department ""%s"" doesn't exist.\n\n", dname);
}
else
(*succ) = 1;
}
else
printf("The department ""%s"" doesn't exist\n\n", dname);
if ((*succ) == 1)
return 0;
else
return -1;
}
int SearchForDelDepartments(struct CompanyType s[], char * dname, int maxit1, int maxit2, int a, int *succ, int *i, int*j)
{
int check = 0;
while((*j) <= maxit1)
{
while((*i) <= maxit2)
{
if(CompareName(s[(*i)].Dep[(*j)].DepName, dname)== 0)
{
check = 1;
break;
}
(*i)++;
}
if(check == 1)
break;
(*j)++;
}
if(check == 1)
{
if(s[(*i)].Dep[(*j)].dflag == 1)
{
(*succ) = 1;
}
}
else
printf("The department ""%s"" doesn't exist\n\n", dname);
if ((*succ) == 1)
return 0;
else
return -1;
}
void DeleteDepartments(struct CompanyType s[], int maxit1, int maxit2, int a, char * dname)
{
int n, i = 0, j = 0;
int succ = 0;
n = SearchForDepartments(s, dname, maxit1, maxit2, a, &succ, &i, &j);
if(n == -1)
return -1;
if(succ == 1)
{
s[i].Dep[j].dflag = 1;
printf("The department %s was deleted from the %s company\n", dname, s[i].CompName);
}
}
void UnDeleteDepartments(struct CompanyType s[], int maxit1, int maxit2, int a, char * dname)
{
int n, i = 0, j = 0;
int succ = 0;
n = SearchForDelDepartments(s, dname, maxit1, maxit2, a, &succ, &i, &j);
if(n == -1)
return -1;
if(succ == 1)
s[i].Dep[j].dflag = 0;
if(s[i].Dep[j].dflag == 0)
printf("The department %s was undeleted\n", dname);
}
ExportListOfCompanyData(struct CompanyType s[], int maxit1, int maxit2, char * FileName)
{
FILE *fp;
fp = fopen(FileName, "w");
if (fp==NULL)
{
printf("Error creating the file \n");
return -1;
}
int flag = 0, i = 0;
while(i <= maxit1)
{
if(s[i].flag == 1)
{
flag = 1;
break;
}
fprintf(fp,"%s\n", s[i].CompName);
fprintf(fp,"%s\n", s[i].OwnerName);
fprintf(fp,"%d\n", s[i].Year);
fprintf(fp,"%.2lf\n\n", s[i].StockPrice);
int j = 0;
while(j < maxit2)
{
if(s[i].Dep[j].dflag == 1)
{
flag = 1;
break;
}
fprintf(fp,"%s\n", s[i].Dep[j].DepName);
fprintf(fp,"%d\n", s[i].Dep[j].NuEmp);
fprintf(fp,"%.2lf\n\n", s[i].Dep[j].Budget);
j++;
}
i++;
}
if(flag == 1)
return -1;
else
return 0;
fclose(fp);
}
char * GetString(FILE *fp)
{
char * str; char c;
str = (char *)malloc(sizeof(char)* MAXNUM);
while(c != '\n')
{
c = fgetc(fp);
printf("%c", c);
}
}
ImportListOfCompanyData(char *FileName, struct CompanyType s[], int maxit1, int maxit2)
{
FILE * fp;
char c, *str;
str = (char *)malloc(sizeof(char)* MAXNUM);
fp = fopen(FileName, "r");
if (fp==NULL)
{
printf("Error creating the file \n");
exit(1);
}
int i = 0, j = 0, n;
GetString(fp);
fclose(fp);
return 0;
}
int main()
{
struct CompanyType CompanyList[MAXNUM];
CreateCompany(CompanyList, "alara inc", "alara", 2020, 6969, 0);
CreateCompany(CompanyList, "Shah inc", "shah", 2020, 3245, 1);
DeleteCompany(CompanyList, "Shah inc", 1);
SearchForCompany(CompanyList, "Shah inc", 1, 1);
UnDeleteCompany(CompanyList, "Shah inc", 1);
SearchForCompany(CompanyList, "Shah inc", 1, 1);
SearchForCompany(CompanyList, "alara inc", 1, 1);
AddDeparments(CompanyList, "alara inc", 1, 0, "computer", 20, 300, 0);
AddDeparments(CompanyList, "Shah inc", 1, 0, "chemistry", 30, 450, 0);
DeleteDepartments(CompanyList, 0, 1, 0, "chemistry");
UnDeleteDepartments(CompanyList, 0, 1, 0, "computer");
PrintCompany(CompanyList, 1, 1);
UnDeleteDepartments(CompanyList, 0, 1, 0, "chemistry");
ExportListOfCompanyData(CompanyList, 1, 1, "Data.txt");
ImportListOfCompanyData("Data.txt", CompanyList, 1, 1);
PrintCompany(CompanyList, 1, 1);
return 0;
}```
It was a really easy solution. I replaced "w" and "r" with "a+"
I guess it was a stupid question, still learning!
I am reading from a txt file into an array of structures. Example txt:
-4.5 -1 0 0
4.0 1 0 0
8 0 1 2
12.1 0 -6 1
-3.2 2.5 -3.0 4
The 4 values of each line correspond to the 4 values in the structure. The file may contain up to 100 lines (MAX is defined as 100). With the following code I am trying to store each line into the respective index of the struct array and then print:
FILE *fileName = NULL;
typedef struct chargeData_struct {
double Q, x, y, z;
} ChargeData;
ChargeData values[MAX], *p = values;
fileName = fopen("charge2.txt", "r");
if (fileName == NULL)
{
printf("ERROR: Could not open file.");
}
int k = 0;
while (fscanf(fileName, "%lf %lf %lf %lf", &p[k].Q, &p[k].x, &p[k].y, &p[k].z) != EOF);
{
printf("%f %f %f %f\n", p[k].Q, p[k].x, p[k].y, p[k].z);
k++;
}
fclose(fileName);
However, only the last line of the txt file is printed. Is the same index of the struct array being overwritten each time?
You are using an extra semicolon which makes all the trouble, here:
while (fscanf(...) != EOF);
{
...
Remove it and you should be fine.
What happens with your code is that while(..); is equivalent to this:
while(...)
{
; // do nothing
}
thus does not enter the body (the one you think is the body) of your loop (since the actual body does nothing). However scanf() continues to parse the file, and then this section of your code executes:
{
printf("%f %f %f %f\n", p[k].Q, p[k].x, p[k].y, p[k].z);
k++;
}
independently, where the curly braces are treated like they wanted to state scope.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define LINE_BUFFER_LEN (512)
#define RESERVE_NEWLINDE 0
#define AUTO_FILTER_NEWLINDE 1
typedef int (* LINE_READER)(char * pstrLine, int uiBufferLen, void * pvData);
typedef struct st_HW_SSP_CONFIG
{
const char * pstrConfigPath;
LINE_READER pfLineReader;
FILE * pstFile;
void * pvData;
int CurrentLine;
int Flag;
} CONFIG_ST;
int CloseConfig(CONFIG_ST * pstConfig)
{
if (!pstConfig)
{
// record error
return -1;
}
if (fclose(pstConfig->pstFile))
{
// record error
}
return 0;
}
int OpenConfigFile(const char * pstrFilePath, CONFIG_ST * pstConfig)
{
FILE * pstFile = NULL;
if ((!pstrFilePath) || (!pstConfig))
{
return -1;
}
pstFile = fopen(pstrFilePath, "r");
if (!pstFile)
{
return -1;
}
pstConfig->pstFile = pstFile;
pstConfig->pstrConfigPath = pstrFilePath;
pstConfig->Flag = RESERVE_NEWLINDE;
return 0;
}
int IsNullStr(const char *pcStr)
{
const char *pcTmp = pcStr;
while ('\0' != *pcTmp)
{
if (!isspace(*pcTmp))
{
return 0;
}
pcTmp++;
}
return 1;
}
int IsEffectiveLine(char acFileLineBuffer[LINE_BUFFER_LEN])
{
if (0 == strlen(&acFileLineBuffer[0]))
{
return 0;
}
if ('#' == acFileLineBuffer[0]) // strip as a comment line
{
return 0;
}
if (IsNullStr(&acFileLineBuffer[0]))
{
return 0;
}
return 1;
}
void FilterNewLine(char* pcLine, int MaxNumLen)
{
int uiLen = strlen(pcLine);
if (uiLen > 1)
{
if ('\n' == pcLine[uiLen - 1])
{
pcLine[uiLen - 1] = '\0';
if (uiLen > 2)
{
if ('\r' == pcLine[uiLen - 2])
{
pcLine[uiLen - 2] = '\0';
}
}
}
}
return;
}
int ReadConfigFile(CONFIG_ST * pstConfig)
{
char acFileLineBuffer[LINE_BUFFER_LEN] = {0};
char * pstrRead = NULL;
int Ret = 0;
if (!pstConfig)
{
return -1;
}
if ((!pstConfig->pstFile) || (!pstConfig->pfLineReader))
{
return -1;
}
rewind(pstConfig->pstFile);
pstConfig->CurrentLine = 0;
do
{
memset((void *)&acFileLineBuffer[0], 0, LINE_BUFFER_LEN);
pstrRead = fgets(&acFileLineBuffer[0], LINE_BUFFER_LEN - 1, pstConfig->pstFile);
if (pstrRead)
{
pstConfig->CurrentLine ++;
if (0 == IsEffectiveLine(acFileLineBuffer))
{
continue;
}
if (AUTO_FILTER_NEWLINDE == pstConfig->Flag)
{
FilterNewLine(acFileLineBuffer, LINE_BUFFER_LEN - 1);
}
if (pstConfig->pfLineReader)
{
Ret = pstConfig->pfLineReader(&acFileLineBuffer[0],
LINE_BUFFER_LEN,
pstConfig->pvData);
if (Ret)
{
break;
}
}
}
}
while (pstrRead);
return Ret;
}
int ReadConfigFileEx(const char * pFilePath,
LINE_READER pfReader,
void * pData, int Flag)
{
int Ret = 0;
CONFIG_ST stConfig = {0};
Ret = OpenConfigFile(pFilePath, &stConfig);
if (Ret)
{
return Ret;
}
stConfig.pfLineReader = pfReader;
stConfig.pvData = pData;
stConfig.Flag = Flag;
Ret = ReadConfigFile(&stConfig);
CloseConfig(&stConfig);
return Ret;
}
int StringSplit(char *pcStr, char cFlag,
char * pstArray[], int MaxNum,
int *pNum)
{
char * pcStrTemp = 0;
unsigned int uiIndex = 0;
pcStrTemp = pcStr;
while (pcStrTemp)
{
pstArray[uiIndex] = pcStrTemp;
pcStrTemp = strchr(pcStrTemp, cFlag);
if (pcStrTemp)
{
*pcStrTemp = '\0';
pcStrTemp ++;
uiIndex ++;
}
if (uiIndex >= MaxNum)
{
break;
}
}
if (0 != MaxNum)
{
*pNum = uiIndex >= MaxNum ? (MaxNum - 1) : uiIndex;
}
else
{
*pNum = 0;
}
return 0;
}
int MyLineReader(char * pstrLine, int uiBufferLen, void * pvData)
{
printf("Read line:[%s]\r\n", pstrLine);
char *pArray[8] = {0};
int Num = 0;
int index = 0;
StringSplit(pstrLine, ' ', pArray, 8, &Num);
for (index = 0; index <= Num; index ++)
{
printf("Get value :[%s]\r\n", pArray[index]);
}
return 0;
}
int main(int argc, char * argv[])
{
int ret = 0;
if (argc != 2)
{
printf("Please input file to read.\r\n");
return 0;
}
ret = ReadConfigFileEx(argv[1], MyLineReader, NULL, AUTO_FILTER_NEWLINDE);
if (ret)
{
printf("Open file error.\r\n");
}
return 0;
}
C noob over here. Created a program that simulates a soccer team to help me get a handle on memory allocation. My program works but valgrind is telling me that I have a memory leak in the methods "create_player" and "add_player_to_club"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 8
typedef struct player {
int id;
char *position;
} Player;
typedef struct club {
int size;
Player *team[SIZE];
} Club;
Player *create_player(int id, const char *description);
void create_team(Club *club);
void print_club(const Club *club);
void destroy_player(Player *player);
void add_player_to_club(Club *club, int id, const char *position);
void destroy_club(Club *club);
int main() {
Club club;
create_team(&club);
add_player_to_club(&club, 1, "forward");
add_player_to_club(&club, 2, "goalie");
print_club(&club);
destroy_club(&club);
return 0;
}
Player *create_player(int id, const char *description){
Player *player;
player = malloc(sizeof(Player));
if(description == NULL){
player->position = NULL;
} else {
player->position = malloc(strlen(description) + 1);
strcpy(player->position, description);
player->id = id;
}
return player;
}
void destroy_player(Player *player){
if (player == NULL){
return;
} else {
free(player->position);
free(player);
}
}
void create_team(Club *team){
team->size = 0;
}
void print_club(const Club *club) {
int i = 0;
if (club == NULL) {
return;
} else if (club->size == 0) {
printf("No team members\n");
} else {
for (i = 0; i < club->size; i++) {
printf("Id: %d Position: %s\n", club->team[i]->id,
club->team[i]->position);
}
}
}
void add_player_to_club(Club *club, int id, const char *position){
if (club == NULL || club->size >= SIZE) {
return;
} else {
club->team[club->size] = create_player(id, position);
club->size++;
}
}
void destroy_club(Club *club){
int i = 0;
if (club == NULL) {
return;
} else {
club->size = 0;
for (i = 0; i < club->size; i++) {
destroy_player(club->team[i]);
}
}
}
I think the problem might be with my "destroy club" method. Player "objects" are stored in the "team" array. I allocated memory for each player object and deallocating by iterating through team array and freeing each index. What did I screw up?
In destroy_club, you set size to 0, then use that to loop through the players, so it loops through nothing.
Set size to 0 after cleaning up the players:
for (i = 0; i < club->size; i++) {
destroy_player(club->team[i]);
}
club->size = 0;
in the following code when ran will produce a Segmentation Fault, due to a FILE* being passed to fclose which contains no address (NULL).
I'm wondering why this is happening, the FILE* isn't being used what so over.
The FILE* is named urandom and is passed to fclose in the main function.
Thanks
#include <stdio.h>
#include <stdlib.h>
struct property
{
char *name;
unsigned int value;
unsigned int owner;
unsigned int type;
};
struct player
{
unsigned int id;
unsigned int money;
unsigned int position;
};
int rollDice(FILE *);
int amountOfLines(FILE *);
int createArrayOfPtrs(int ,void ***);
int makeArryOfPropertyPtrs(int ,struct property **);
int FillArryPropertyData(struct property **,int ,FILE *);
int splitBuffer(char *,unsigned int *,char **);
int bufferPropertyFile(FILE *,char **,int );
i nt fillPropertyStruct(struct property *,unsigned int ,char *);
int main(void)
{
int linesInPropertyFile = 0;
struct property **arrayForProperties = 0;
//Open /dev/urandom for rollDice
FILE *urandom = fopen("/dev/urandom","rb");
FILE *propertyFile = fopen("/home/jordan/Documents/Programming/Monopoly Project/properties","rb");
if(propertyFile == NULL || urandom == NULL)
{
puts("ERROR: error in opening file(s)");
return 1;
}
linesInPropertyFile = amountOfLines(propertyFile);
//DEBUG
printf("%d is contained within \"linesInPropertyFile\"\n",linesInPropertyFile);
if(createArrayOfPtrs(linesInPropertyFile,(void ***)&arrayForProperties))
{
puts("ERROR: error from createArrayOfPointers()");
return 1;
}
//DEBUG
printf("Outside Pointer: %p\n",arrayForProperties);
if(makeArryOfPropertyPtrs(linesInPropertyFile,arrayForProperties))
{
puts("ERROR: error from createArrayOfPointersForProperties()");
return 1;
}
if(FillArryPropertyData(arrayForProperties,linesInPropertyFile,propertyFile))
{
puts("ERROR: error from FillArryPropertyData()");
}
//Close FILE stream for /dev/urandom
fclose(urandom);
fclose(propertyFile);
return 0;
}
int FillArryPropertyData(struct property **array,int amntOfProperties,FILE *fp)
{
int bufferUsed = 100;
int i = 0;
int returnValue = 0;
int returnValue2 = 0;
unsigned int money = 0;
char *name;
char *buffer;
rewind(fp);
while(returnValue == 0)
{
buffer = malloc(bufferUsed);
returnValue = bufferPropertyFile(fp,&buffer,bufferUsed);
if(returnValue && returnValue != -1)
{
puts("ERROR: error from bufferPropertyFile()");
return -1;
}
if(returnValue == -1)
{
break;
}
if(buffer[0] != '\0')
{
returnValue2 = splitBuffer(buffer,&money,&name);
}
if(returnValue2)
{
puts("ERROR: error in splitBuffer()");
return 1;
}
if(fillPropertyStruct(array[i],money,name))
{
puts("ERROR: error in fillPropertyStruct()");
return 1;
}
money = 0;
i++;
}
free(buffer);
return 0;
}
int fillPropertyStruct(struct property *array,unsigned int money,char *name)
{
int nameSize = 100;
int i = 0;
array->name = malloc(nameSize);
array->value = money;
while(1)
{
if(i >= nameSize)
{
void *tmp = realloc(array->name,nameSize * 2);
nameSize *= 2;
if(tmp)
{
array->name = tmp;
}
else
{
return -1;
}
}
if(name[i] == '\0')
{
break;
}
array->name[i] = name[i];
i++;
}
array->name[i] = '\0';
return 0;
}
int splitBuffer(char *buffer,unsigned int *money,char **name)
{
int i = 0;
int j = 1;
int nameSize = 100;
*name = malloc(nameSize);
while(1)
{
if(buffer[j] != '"')
{
(*name)[j-1] = buffer[j];
}
else
{
i++;
}
j++;
if(i)
{
break;
}
if(j >= nameSize)
{
void *tmp = 0;
tmp = realloc(*name,nameSize * 2);
nameSize = nameSize * 2;
if(tmp != NULL)
{
*name = tmp;
}
else
{
puts("ERROR: error in splitBuffer");
return -1;
}
}
}
name[j-1] = '\0';
while(buffer[j] != '$')
{
if(buffer[j] == '\0')
{
puts("ERROR: error in splitBuffer()");
return -2;
}
j++;
}
j++;
while(buffer[j] != '\0')
{
*money += (buffer[j] - '0');
if(buffer[j+1] != '\0')
{
*money *= 10;
}
j++;
}
printf("BUFFER: %s\n",buffer);
printf("NAME: %s\n",*name);
printf("MONEY: %d\n",*money);
return 0;
}
int bufferPropertyFile(FILE *fp,char **buffer,int i)
{
int j = (i - i);
if(feof(fp))
{
//-1 Returned if EOF detected
return -1;
}
char retr = 0;
while(1)
{
if(j + 1 >= i)
{
void *tmp = realloc(*buffer,i * 2);
if(tmp != NULL)
{
*buffer = tmp;
i = i * 2;
}
else
{
puts("ERROR: error in bufferPropertyFile()");
return -2;
}
}
retr = fgetc(fp);
if(retr == '\n' || feof(fp))
{
break;
}
(*buffer)[j] = retr;
j++;
}
(*buffer)[j] = '\0';
if(**buffer == '\0')
{
return -1;
}
return 0;
}
int rollDice(FILE *fp)
{
int seed = fgetc(fp);
srand(seed);
return (rand() % 6) + 1;
}
int amountOfLines(FILE *file)
{
int i = 0;
int retr = 0;
while(1)
{
retr = fgetc(file);
if(retr == EOF)
{
break;
}
if(retr == '\n' )
{
i++;
}
}
return i;
}
int createArrayOfPtrs(int numberOfPointers,void ***pointer)
{
void *tmp = malloc(numberOfPointers * sizeof (tmp));
if(tmp != NULL)
{
*pointer = tmp;
//DEBUG
printf("Pointer: %p\n",*pointer);
}
else
{
return 1;
}
return 0;
}
int makeArryOfPropertyPtrs(int numberOfPointers,struct property **pointer)
{
int i = 0;
void *tmp;
for(i = 0;i < numberOfPointers;i++)
{
tmp = malloc(sizeof(struct property));
if(tmp == NULL)
{
return 1;
}
pointer[i] = (struct property *)tmp;
}
return 0;
}
here it givest an access violation in splitBuffer on this line:
name[j-1]='\0';
which probably should be
(*name)[j-1]='\0';
indeed that memory is not allocated anywhere, in other words, undefined behaviour, which indeed in your case might overwrite the urandom variable: both urandom and name are allocated on stack so depending on value of j it might write over urandom..
apart from that, there might be more errors, the number and use of pointers/mallocs/reallocs and lack of frees is a bit scary
int createArrayOfPtrs(int ,void ***);
if(createArrayOfPtrs(linesInPropertyFile,(void ***)&arrayForProperties))
This is undefined behaviour, a (void***) is not compatible to a (struct property ***). Why do you even use it here, all the other functions use struct property pointers?
Since the array is located right before the file pointer in the local variables of main, maybe the problem is that the array creation/initialization overwrites urandom?