I am having trouble making a function that will open a file - c

void writeResultsToFile(FILE *f, char arrTypeLabels[3][7], char sortNames[4][11], float times[4][3], int n);
void writeResultsToFile(FILE *f, char arrTypeLabels[3][7], char sortNames[4][11], float times[4][3], int n)
{
f= fopen( "TIMES.txt", "wb");
if((f=fopen("TIMES.txt", "wb"))==NULL) {
printf("Cannot open file.n");
}
if (f == NULL)
{
printf("Error! Could not open file\n");
exit(-1);
}
fprintf(f,"Array size: %d\n================\n ",n);
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<7;j++)
{
fwrite(arrTypeLabels[i] + j, sizeof (char), sizeof (char), f);
}
}
for(i=0;i<4;i++)
{
for(j=0;j<11;j++)
{
fwrite(sortNames[i] + j, sizeof (char), sizeof (char), f);
if (j==9 && i==0)
{
int df;
for(df=0;df<3;df++)
fprintf(f," %f",times[0][df]);
}
if (j==9 && i==1)
{
int df;
for(df=0;df<3;df++)
fprintf(f," %f",times[1][df]);
}
if (j==5 && i==2)
{
int df;
fprintf(f," ");
for(df=0;df<3;df++)
fprintf(f," %f",times[2][df]);
}
if (j==5 && i==3)
{
int df;
fprintf(f," ");
for(df=0;df<3;df++)
fprintf(f," %f",times[3][df]);
}
}
}
fclose(f);
}
//This is how i call it inside the main
writeResultsToFile(FILE *f,arrTypeLabels[3][7],sortNames[4][11],times[4][3],n);
the code inside it is right i tested it without the funtion, it works , i just dont know how to call it as a funtion if anybody can help.
Expected expression before FILE, and conflicted type errors..............................................

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void writeResultsToFile(FILE *f, char arrTypeLabels[3][7], char
sortNames[4][11], float times[4][3], int n);
int main(int argc, char *argv[])
{
int n=10;
char arrTypeLabels[3][7]= {"Random", "ASC", "DESC"},sortNames[4]
[11]={"Selection", "Insertion", "Shell", "Quick"};
FILE *f;
float times[4][3];
writeResultsToFile(f, arrTypeLabels, sortNames, times, n);
return 0;
}
void writeResultsToFile(FILE *f, char arrTypeLabels[3][7], char
sortNames[4][11], float times[4][3], int n)
{
f= fopen( "TIMES.txt", "wb");
if((f=fopen("TIMES.txt", "wb"))==NULL) {
printf("Cannot open file.n");
}
if (f == NULL)
{
printf("Error! Could not open file\n");
exit(-1);
}
fprintf(f,"Array size: %d\n================\n ",n);
int i,j;
for(i=0;i<3;i++)
{
if(i==2){
fprintf(f," %s ",arrTypeLabels[i]);
}
else{
fprintf(f,"%s ",arrTypeLabels[i]);
}
}
for(i=0;i<4;i++)
{
fprintf(f,"\n");
for(j=0;j<11;j++)
{
fwrite(sortNames[i] + j, sizeof (char), sizeof (char), f);
if (j==9 && i==0)
{
int df;
for(df=0;df<3;df++)
fprintf(f," %f",times[0][df]);
}
if (j==9 && i==1)
{
int df;
for(df=0;df<3;df++)
fprintf(f," %f",times[1][df]);
}
if (j==5 && i==2)
{
int df;
fprintf(f," ");
for(df=0;df<3;df++)
fprintf(f," %f",times[2][df]);
}
if (j==5 && i==3)
{
int df;
fprintf(f," ");
for(df=0;df<3;df++)
fprintf(f," %f",times[3][df]);
}
}
}
fclose(f);
}

#include <stdlib.h>
#include <wchar.h>
#include <stdio.h>
int writeResultsToFile(FILE *f, char arrTypeLabels[3][7], char sortNames[4][11], float times[4][3], int n);
int writeResultsToFile(FILE *f, char arrTypeLabels[3][7], char sortNames[4][11], float times[4][3], int n)
{
f = fopen("TIMES.txt", "wb");
if ((f = fopen("TIMES.txt", "wb")) == NULL)
{
printf("Cannot open file.n");
}
if (f == NULL)
{
printf("Error! Could not open file\n");
exit(-1);
}
fprintf(f, "Array size: %d\n================\n ", n);
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 7; j++)
{
fwrite(arrTypeLabels[i] + j, sizeof (char), sizeof (char), f);
}
}
for (i = 0; i < 4; i++)
{
for (j = 0; j < 11; j++)
{
fwrite(sortNames[i] + j, sizeof (char), sizeof (char), f);
if (j == 9 && i == 0)
{
int df;
for (df = 0; df < 3; df++)
fprintf(f, " %f", times[0][df]);
}
if (j == 9 && i == 1)
{
int df;
for (df = 0; df < 3; df++)
fprintf(f, " %f", times[1][df]);
}
if (j == 5 && i == 2)
{
int df;
fprintf(f, " ");
for (df = 0; df < 3; df++)
fprintf(f, " %f", times[2][df]);
}
if (j == 5 && i == 3)
{
int df;
fprintf(f, " ");
for (df = 0; df < 3; df++)
fprintf(f, " %f", times[3][df]);
}
}
}
fclose(f);
}
int main(void)
{
//assign theses variables before calling your function
char arrTypeLabels[3][7];
char sortNames[4][11];
float times[4][3];
int n;
//--------------------------
FILE * f; //no need to assign this variable
writeResultsToFile(f, arrTypeLabels, sortNames, times, n); //call your function like that
return 0;
}

Related

is there a replacement for argc and argv

I have a C program here where a warehouse is managed. I want to use argc and argv in this code, because the program always expects the commands as call parameters, not as interactive input. And I want to be able to enter them as interactive input.
How should it be changed? I am completely new to C or programming in general.
sorry in the code some words are not in english
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAMELENGTH 100
#define DBSIZE 1000
#define DBNAME "database.bin"
struct Artikel
{
char artikel[NAMELENGTH + 1];
int anzahl;
};
struct Artikel db[DBSIZE];
void fehler(const char *text)
{
fprintf(stderr, "Fehler: %s!\n", text);
exit(1);
}
void check_artikel(char *artikel)
{
if (!artikel || strlen(artikel) > NAMELENGTH)
fehler("Artikel zu lang");
}
void db_load()
{
FILE *input = fopen(DBNAME, "rb");
if (!input)
fehler("Datenbank zum Lesen öffnen fehlgeschlagen");
size_t size = fread(db, 1, sizeof(db), input);
if (size != sizeof(db))
fehler("Datenbank nicht komplett geladen");
fclose(input);
}
void db_save()
{
FILE *output = fopen(DBNAME, "wb");
if (!output)
fehler("Datenbank zum Schreiben öffnen fehlgelschlagen");
size_t size = fwrite(db, 1, sizeof(db), output);
if (size != sizeof(db))
fehler("Datenbank nicht komplett geschrieben");
fclose(output);
}
void db_clear()
{
for (int i = 0; i < DBSIZE; i++)
{
db[i].anzahl = 0;
}
}
int db_size()
{
int size = 0;
for (int i = 0; i < DBSIZE; i++)
size += db[i].anzahl ? 1 : 0;
return size;
}
int db_find(char *artikel)
{
for (int i = 0; i < DBSIZE; i++)
if (db[i].anzahl > 0 && !strcasecmp(db[i].artikel, artikel))
return i;
return -1;
}
void db_add(char *artikel, int anzahl)
{
int found = db_find(artikel);
if (found >= 0)
{
db[found].anzahl += anzahl;
return;
}
for (int i = 0; i < DBSIZE; i++)
if (db[i].anzahl == 0)
{
strcpy(db[i].artikel, artikel);
db[i].anzahl = anzahl;
return;
}
fprintf(stderr, "Datenbank voll!\n");
}
void db_list()
{
if (db_size() == 0)
{
printf("Datenbank ist leer.\n");
return;
}
printf("Anzahl : Artikel\n");
printf("--------:-------------------------------------------------------------\n");
for (int i = 0; i < DBSIZE; i++)
if (db[i].anzahl > 0)
{
printf(" %5d : %s\n", db[i].anzahl, db[i].artikel);
}
}
int main(int argc, char **argv)
{
if (argc < 2)
fehler("Kein Kommando angegeben!\nGültige Kommandos: init, add ANZAHL ARTIKEL, list");
const char *cmd = argv[1];
if (!strcmp(cmd, "init"))
{
db_clear();
db_save();
printf("Datenbank initialisiert.\n");
}
else if (!strcmp(cmd, "list"))
{
db_load();
db_list();
}
else if (!strcmp(cmd, "add"))
{
if (argc < 3)
fehler("Keine Artikelanzahl angegeben");
int anzahl = atoi(argv[2]);
if (anzahl <= 0)
fehler("Artikelanzahl zu klein");
if (argc < 4)
fehler("Kein Artikel angegeben");
char *artikel = argv[3];
check_artikel(artikel);
if (argc > 4)
fehler("Zu viele Eingaben");
db_load();
db_add(artikel, anzahl);
db_save();
printf("Artikel hinzugefügt.\n");
}
else
{
fprintf(stderr, "Unbekanntes Kommando!\n");
return 1;
}
return 0;
}

Why is does the file become NULL?

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!

Game of Life .exe strange output

I wrote a C code for a Game of Life simulation. My program works perfectly fine for case 1 which is my random array. But it doesn't work when I try to load an array out of a .txt file. I mean it gives me an output but it doesn't output an array with '*' or ' ' it gives me this:
Does someone know what my mistake is?
Here´s my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <Windows.h>
#define ED 25
#define ZD 25
// - FUNCTIONS
void print_matr(char matr[ED][ZD], int n, int m);
void create_matr(char matr[ED][ZD], int n, int m, int *alz, int prozent);
void check_neighbours(char matr[ED][ZD], int n, int m, char lager[ED][ZD], int *alz);
void ausfuehren(char matr[ED][ZD], int n, int m, char lager[ED][ZD], int *alz);
void load_matr(char matr[ED][ZD], int n, int m, int filenr, int *alz);
int Menu(char *text, int anz, char *prompt);
int check_rules(char matr[ED][ZD], int n, int m, char lager[ED][ZD], int lx, int ly, int alz);
int Einlesen(char *prompt, int min, int max, int versuche);
// -MAIN-
int main() {
const int n = ED; const int m = ZD; //1.Dim/2.Dim
char matr[ED][ZD];
char lager[ED][ZD];
int alz; //Anzahl lebender Zellen
int prozent;
switch (Menu("\n1 - random\n2 - load array 1\n3 - load array 2\n4 - load array 3\n\n0 - exit", 5, "\n >>>> ")) {
case 0: exit(0); break;
case 1:
prozent = Einlesen("Percentage? ", 0, 100, 5);
create_matr(matr, n, m, &alz, prozent);
print_matr(matr, n, m);
ausfuehren(matr, n, m, lager, &alz);
break;
case 2:
load_matr(matr, n, m, 1,&alz);
print_matr(matr, n, m);
ausfuehren(matr, n, m, lager, &alz); break;
case 3:
load_matr(matr, n, m, 2,&alz);
print_matr(matr, n, m);
ausfuehren(matr, n, m, lager, &alz); break;
case 4:
load_matr(matr, n, m, 3, &alz);
print_matr(matr, n, m);
ausfuehren(matr, n, m, lager, &alz);
break;
}
return 0;
}
// -PRINT
void print_matr(char matr[ED][ZD], int n, int m) {
for (int lx = 0; lx < n; lx++) {
for (int ly = 0; ly < m; ly++) {
printf(" %c", matr[lx][ly]);
}
printf("\n");
}
printf("\n\n");
}
int Einlesen(char *prompt, int min, int max, int versuche) {
int zahl;
fflush(stdin);
if (!versuche) {
exit(0);
}
printf(prompt);
if (!scanf("%d", &zahl)) {
printf(" *** Bitte Zahl eingeben! ***\n");
return Einlesen(prompt, min, max, versuche - 1);
}
if ((zahl<min) || (zahl>max)) {
printf(" *** [%d,%d]! ***\n", min, max);
return Einlesen(prompt, min, max, versuche - 1);
}
return zahl;
}
int Menu(char *text, int anz, char *prompt) {
printf(text);
return Einlesen(prompt, 0, anz, 5);
}
void create_matr(char matr[ED][ZD], int n, int m, int *alz, int prozent) {
for (int ln = 0; ln < n; ln++) {
for (int lm = 0; lm < m; lm++) {
if (rand()%100 <= prozent) {
matr[ln][lm] = '*';
(*alz)++;
}
else { matr[ln][lm] = ' ';}
}
}
}
int check_rules(char matr[ED][ZD], int n, int m, char lager[ED][ZD], int lx, int ly, int l_anzlz) {
//Rule 1
if (matr[lx][ly] == '*') {
if ((l_anzlz == 0) || (l_anzlz == 1) || (l_anzlz > 3)) {
lager[lx][ly] = ' ';
}
//Rule 2
else if ((l_anzlz == 2) || (l_anzlz == 3)) {
lager[lx][ly] = '*';
}
}
//Rule 3
else if (matr[lx][ly] == ' ') {
if (l_anzlz == 3) {
lager[lx][ly] = '*';
}
else lager[lx][ly] = ' ';
}
return 1;
}
void check_neighbours(char matr[ED][ZD], int n, int m, char lager[ED][ZD], int *alz) {
int counteq = 0;
int l_anzlz;
(*alz)=0;
for(int lx = 0; lx < n; lx++) {
for(int ly = 0; ly < m; ly++) {
l_anzlz = 0;
for(int la = -1; la <= 1; la++) {
for(int lb = -1; lb <= 1; lb++) {
if((la==0)&&(lb==0)) continue;
if((lx==0)&&(la==-1)) continue;
if((lx==n-1)&&(la==1)) continue;
if((ly==0)&&(lb==-1)) continue;
if((ly==m-1)&&(lb==1)) continue;
if (matr[lx + la][ly + lb] == '*') {
l_anzlz++;
}
}
}
check_rules(matr, n, m, lager, lx, ly, l_anzlz);
}
}
//printf("lager\n");
//print_matr(lager, n, m);
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++) {
if (matr[i][j] == lager[i][j]) {
counteq++;
}
matr[i][j] = lager[i][j];
if (matr[i][j] == '*') (*alz)++;
}
}
if (counteq == (n*m)) (*alz)=0;
}
// -EXECUTE
void ausfuehren(char matr[ED][ZD], int n, int m, char lager[ED][ZD], int *alz) {
char eing;
int fors;
fors = Einlesen(" [0] or [1]?\n", 0, 1, 2);
if(fors==1) printf(" 'q' to end \n");
while ((*alz) > 0) {
check_neighbours(matr, n, m, lager, alz); /
print_matr(matr, n, m);
if (fors == 0) {
Sleep(300);
}
else if (fors == 1) {
fflush(stdin);
scanf("%c", &eing);
if(eing=='q') break;
}
}
}
void load_matr(char matr[ED][ZD], int n, int m, int filenr, int *alz) {
FILE *fp;
char c[4];
(*alz)=0;
if (filenr == 1) {
fp = fopen("matrix1.txt", "rt");
}
else if (filenr == 2) {
fp = fopen("matrix2.txt", "rt");
}
else if (filenr == 3) {
fp = fopen("matrix3.txt", "rt");
}
if(fp==0){
printf("Couldnt open File!");
exit(-1);
}
if(fgets(c, 5, fp)==NULL){
printf("Error\n");
exit(-1);
}
n=(int)(*c);
if(fgets(c, 5, fp)==NULL){
printf("Error\n");
exit(-1);
}
m=(int)(*c);
for (int lx = 0; lx < n; lx++) {
for (int ly = 0; ly < m; ly++) {
int star = fgetc(fp);
if (star == 42) { //42=* | ASCII
matr[lx][ly] = '*';
(*alz)++;
}
else if (star == 32) { //32= | ASCII
matr[lx][ly] = ' ';
}
else if (star == 10) { //10=\n | ASCII
lx--; ly = m - 1;
}
else break; //EOF
}
}
fclose(fp);
}
Would appreciate any help!
Thanks!
Your problem is into the load_matr function:
This is a possible solution, that make it works when the input file is properly formatted (it is not a solution fault tolerant), and many bad things, but it works.
void clear_matr(char matr[ED][ZD])
{
for (int row = 0; row < ED; row++)
for (int col = 0; col < ZD; col++)
matr[row][col] = ' ';
}
void load_matr(char matr[ED][ZD], int n, int m, int filenr, int *alz) {
FILE *fp;
char c[16];
(*alz)=0;
memset(c, 0, sizeof(c));
if (filenr == 1) {
fp = fopen("matrix1.txt", "rt");
}
else if (filenr == 2) {
fp = fopen("matrix2.txt", "rt");
}
else if (filenr == 3) {
fp = fopen("matrix3.txt", "rt");
}
if (fp == 0) {
printf("Couldnt open File!");
exit(-1);
}
if (fgets(c, 5, fp) == NULL) {
printf("Error\n");
exit(-1);
}
n = atoi(c);
if (fgets(c, 5, fp) == NULL) {
printf("Error\n");
exit(-1);
}
m = atoi(c);
clear_matr(matr);
for (int ly = 0; ly < m; ly++) {
for (int lx = 0; lx < n; lx++) {
int star = fgetc(fp);
if (star == '\n')
star = fgetc(fp);
if (star == 42) { //42=* | ASCII
matr[ly][lx] = '*';
(*alz)++;
}
else if (star == 32) { //32= | ASCII
matr[ly][lx] = ' ';
}
else break; //EOF
}
}
fclose(fp);
}

Segmentation fault using fgets in C

My code is not working and it is when I call fgets in the commandSplit function. I figured this out by printing "Am I here" in multiple places and find that the error at fgets it seems. I may be wrong, but I am pretty sure. I get a segmentation fault and I can not figure out why. Below is my code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#define MAX_CHARACTERS 512
int Execute(char *a[], int t[], int num) {
int exitShell = 0;
int l = 0;
for (int i = 0; i < num; i++) {
int status;
if (strcmp(a[0], "quit") == 0) {
exitShell = 1;
}
if (t[i] && ((strcmp(a[l], "quit") == 0))) {
exitShell = 1;
}
char *holder[t[i]+1];
for (int j = 0; j < t[i]; j++) {
holder[j] = a[l];
l++;
}
holder[t[i]] = NULL;
pid_t p = fork();
pid_t waiting;
if (p == 0) {
execvp(holder[0], holder);
fprintf(stderr, "Child process could not execvp!\n");
exit(1);
} else {
if (p < 0) {
fprintf(stderr, "Fork FAILED!\n");
} else {
waiting = wait(&status);
printf("Child %d exit with status %d\n", waiting, status);
}
}
for (int g = 0; g < t[i]; g++) {
a[g] = NULL;
}
}
for (int i = 0; i < num; i++) {
t[i] = 0;
}
return exitShell;
}
int commandSplit(char *c, FILE *f, char *a[], int t[]) {
int count = 0;
int emptyfile = 1;
int stat = 0;
int total1 = 0;
char *temp[MAX_CHARACTERS];
if (c != NULL) {
char *readCommands = strtok(c, ";");
while (readCommands != NULL) {
temp[count] = readCommands;
count++;
readCommands = strtok(NULL, ";");
}
for (int i = 0; i < count; i++) {
char *read = strtok(temp[i], " ");
int track1 = 0;
while (read != NULL) {
a[total1] = read;
track1++;
total1++;
read = strtok(NULL, " ");
}
t[i] = track1;
}
stat = Execute(a, t, count);
} else {
char *buildCommands = "";
printf("Am I here???\n");
while ((fgets(buildCommands, MAX_CHARACTERS, f) != NULL) && !stat) {
printf("Am I here???\n");
emptyfile = 0;
commandSplit(buildCommands, NULL, a, t);
stat = Execute(a, t, count);
}
if (emptyfile) {
printf("File is empty!\n");
stat = 1;
}
}
printf("Am I here???\n");
return stat;
}
int main(int argc, char *argv[]) {
int exitProgram = 0;
FILE *fileRead = NULL;
if (argc == 2) {
fileRead = fopen(argv[1], "r");
if (fileRead == NULL) {
printf("No such file exists\n");
exitProgram = 1;
}
}
if (argc > 2) {
printf("Incorrect batch mode call\n");
exitProgram = 1;
}
char *args[MAX_CHARACTERS];
int tracker[MAX_CHARACTERS];
while (!exitProgram) {
if (argc == 1) {
char *commands = (char *)(malloc(MAX_CHARACTERS * sizeof(char)));
printf("tinyshell>");
if (fgets(commands, MAX_CHARACTERS, stdin) == NULL) {
exitProgram = 1;
printf("\n");
}
int len;
len = strlen(commands);
if (len > 0 && commands[len-1] == '\n') {
commands[len-1] = '\0';
}
if (len > MAX_CHARACTERS) {
printf("TOO MANY CHARACTERS - MAX: 512\n");
continue;
}
if (strlen(commands) == 0)
continue;
exitProgram = commandSplit(commands, NULL, args, tracker);
} else {
exitProgram = commandSplit(NULL, fileRead, args, tracker);
}
}
fclose(fileRead);
return 0;
}
As commented #Jean-François Fabre , buildCommands points to insufficient space and potential const space;
char *buildCommands = "";
...
// bad code
while ((fgets(buildCommands, MAX_CHARACTERS, f) != NULL) && !stat) {
Allocate space with an array or malloc()
char buildCommands[MAX_CHARACTERS];
...
while ((fgets(buildCommands, sizeof buildCommands, f) != NULL) && !stat) {
...
}
// or
char *buildCommands = malloc(MAX_CHARACTERS);
assert(buildCommands);
...
while ((fgets(buildCommands, MAX_CHARACTERS, f) != NULL) && !stat) {
...
}
...
free(buildCommands);

Can't free memory from 2D dynamical array

I am having problem with freeing my memory. I did this many times, and it was working fine. Now, it just stops working (no error, anything, just freeze).
How my code looks like:
void args(int argc, char** argv, int *n, int *m, int **matrix, char name[20])
{
int firstIter = TRUE;
int x;
char op;
int** second;
second = NULL;
op = argv[1][0];
for (x = 2; x < argc; x++)
{
if (!firstIter)
{
setName(name, argv[x]);
loadMatrix(*m, *n, second, *name);
opMatrix(*m, *n, matrix, second, &*matrix, op);
}
else
{
setName(name, argv[x]);
loadSizeMatrix(n, m, name);
matrix = (int **)malloc(*n * sizeof(int*));
for (int i = 0; i < *n; i++) {
matrix[i] = (int *)malloc(*m * sizeof(int));
}
second = (int **)malloc(*n * sizeof(int*));
for (int i = 0; i < *n; i++) {
second[i] = (int *)malloc(*m * sizeof(int));
}
loadMatrix(*m, *n, matrix, *name);
firstIter = FALSE;
}
}
printMatrix(*m, *n, matrix);
for (int i = 0; i < *n; i++) {
free(second[i]);
}
free(second[0]); //doesnt work too, and yes, there are data
free(second);
}
second is being filled like this (loadMatrix):
for (int c = 0; c < radky; c++) {
for (int d = 0; d < sloupce; d++) {
fscanf(fp, "%i", &second[c][d]);
// printf("%i", matice[c][d]); // dump
}
}
How can I solve this error?
my full code
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <ctype.h> //tolower
#include <string.h>
#define TRUE 1
#define FALSE !TRUE
/* konstanty */
const enum {
MAX_DELKA_SOUBORU = 10000,
MAX_SOUBOR = 20
};
const enum {
SOUBOR_NENALEZEN = 1,
SPATNE_ARGUMENTY = 2,
LIMIT_NAZEV_SOUBOR = 3,
SPATNY_OP = 4
};
void error(int type);
void zpracovaniArgumentu(int argc, char** argv, char(*nazevSouboru)[MAX_SOUBOR], char(*nazevVystupni)[MAX_SOUBOR], int *n, int *m, int **matice);
void setNazevSouboru(char(*nazev)[MAX_SOUBOR], char *argument);
void vypisMatice(int radky, int sloupce, int **matice);
int nacteniMaticeZeSouboru(int radky, int sloupce, int **matice, char nazev[MAX_SOUBOR]);
int nacteniVelikostiMatice(int *n, int *m, char nazev[MAX_SOUBOR]);
int operaceMatic(int radky, int sloupce, int **prvni, int **druha, int **vysledek, char op);
int main(int argc, char** argv)
{
int n, m; // n = sloupce, m = radky pro prvni matici
int** first;
char nazevSouboru[MAX_SOUBOR], nazevVystupni[MAX_SOUBOR];
char op;
first = NULL;
zpracovaniArgumentu(argc, argv, &nazevSouboru, &nazevVystupni, &n, &m, &*first);
/* for (int i = 0; i < m; i++) {
free(first[i]);
} */
free(first);
system("pause");
return 0;
}
void error(int type)
{
switch (type)
{
case SOUBOR_NENALEZEN: printf("Soubor nenalezen!");
break;
case SPATNE_ARGUMENTY: printf("Program spustte s argumenty [nazev souboru] *[nazev vystupniho souboru]*.\n");
break;
case MAX_DELKA_SOUBORU: printf("Prekrocen maximalni limit delky nazvu souboru (%i).\n", MAX_SOUBOR);
break;
case SPATNY_OP: printf("Program spustte s argumenty [nazev souboru] *[nazev vystupniho souboru]*.\n");
break;
default: printf("Nastala chyba!");
break;
}
system("pause");
exit(type);
}
void zpracovaniArgumentu(int argc, char** argv, char(*nazevSouboru)[MAX_SOUBOR], char(*nazevVystupni)[MAX_SOUBOR], int *n, int *m, int **matice)
{
int firstIter = TRUE;
int doSouboru = FALSE;
int x;
char op;
int** second;
second = NULL;
op = argv[1][0];
for (x = 2; x < argc; x++)
{
if (!firstIter)
{
setNazevSouboru(nazevSouboru, argv[x]);
nacteniMaticeZeSouboru(*m, *n, &*second, *nazevSouboru);
operaceMatic(*m, *n, matice, &*second, &*matice, op);
}
else if (argv[x][0] == '-')
{
switch (argv[x][1])
{
case 'n': doSouboru = TRUE;
break;
default: error(SPATNE_ARGUMENTY);
break;
}
}
else if (doSouboru)
{
setNazevSouboru(nazevVystupni, argv[x]);
}
else
{
setNazevSouboru(nazevSouboru, argv[x]);
nacteniVelikostiMatice(n, m, *nazevSouboru);
matice = (int **)malloc(*n * sizeof(int*));
for (int i = 0; i < *n; i++) {
matice[i] = (int *)malloc(*m * sizeof(int));
}
second = (int **)malloc(*n * sizeof(int*));
for (int i = 0; i < *n; i++) {
second[i] = (int *)malloc(*m * sizeof(int));
}
nacteniMaticeZeSouboru(*m, *n, &*matice, *nazevSouboru);
firstIter = FALSE;
}
}
vypisMatice(*m, *n, matice);
for (int i = 0; i < *n; i++) {
printf("%i",second[i]);
free(second[i]);
}
free(second);
}
void setNazevSouboru(char(*nazev)[MAX_SOUBOR], char *argument)
{
strcpy(*nazev, argument);
strcat(*nazev, ".txt"); //nazev souboru
}
int nacteniVelikostiMatice(int *n, int *m, char nazev[MAX_SOUBOR])
{
FILE *fp = fopen(nazev, "r"); // načtení souboru
int c;
int radky = 1;
int sloupce = 0;
if (!fp)
{
error(SOUBOR_NENALEZEN);
exit(2);
}
else
{
while ((c = fgetc(fp)) != EOF)
{
//tolower(c);
if (c == '\n')
{
radky++;
}
else if ((isdigit(c)) && (radky == 1))
{
sloupce++;
}
}
}
fclose(fp);
*n = sloupce;
*m = radky;
return 0;
}
int nacteniMaticeZeSouboru(int radky, int sloupce, int **matice, char nazev[MAX_SOUBOR])
{
int x;
FILE *fp = fopen(nazev, "r"); // načtení souboru
if (!fp)
{
error(SOUBOR_NENALEZEN);
exit(2);
}
else
{
for (int c = 0; c < radky; c++) {
for (int d = 0; d < sloupce; d++) {
fscanf(fp, "%i", &matice[c][d]);
// printf("%i", matice[c][d]); // dump
}
}
}
fclose(fp);
return 0;
}
int operaceMatic(int radky, int sloupce, int **prvni, int **druha, int **vysledek, char op)
{
int vysledekClip[10][10];
for (int c = 0; c < radky; c++) {
for (int d = 0; d < sloupce; d++) {
switch (op) {
case '+': vysledekClip[c][d] = prvni[c][d] + druha[c][d];
vysledek[c][d] = vysledekClip[c][d];
break;
case '-': vysledekClip[c][d] = prvni[c][d] - druha[c][d];
vysledek[c][d] = vysledekClip[c][d];
break;
case '/': vysledekClip[c][d] = prvni[c][d] / druha[c][d];
vysledek[c][d] = vysledekClip[c][d];
break;
case '%': vysledekClip[c][d] = prvni[c][d] % druha[c][d];
vysledek[c][d] = vysledekClip[c][d];
break;
case '*': vysledekClip[c][d] = prvni[c][d] * druha[c][d];
vysledek[c][d] = vysledekClip[c][d];
break;
default: error(SPATNY_OP);
break;
}
vysledek[c][d] = vysledekClip[c][d];
}
}
return 0;
}
void vypisMatice(int radky, int sloupce, int **matice)
{
int c;
int d;
for (c = 0; c < radky; c++) {
for (d = 0; d < sloupce; d++) {
printf("%i\t", matice[c][d]);
} printf("\n");
}
}
void vypisMaticeDoSouboru(int radky, int sloupce, int **matice, char nazevSouboru[MAX_DELKA_SOUBORU])
{
int c;
int d;
for (c = 0; c < radky; c++) {
for (d = 0; d < sloupce; d++) {
printf("%i\t", matice[c][d]);
} printf("\n");
}
}
You have a problem with the 'second' array. You allocate an array of *n pointers to int but fill *m elements in that array:
second = (int **) malloc(*n * sizeof(int*));<p>
for (int i = 0; i < *m; i++) {

Resources