i studied c++ before c guess that was my mistake...
i try to read from a file a set of strings and put them
in the new allocated array, i do not understand what is the main thing this
code isnt working. i get segmentation fault...
and even trying to input a character in the array will result in seg fault.
(u call the program with 2 file names and first will be for input
and 2nd for output)
thanks
#include "ex1.h"
void error(char *msg);
void checkFiles(int argc, char *argv[], FILE * *in,FILE * *out);
int main(int argc, char *argv[]) {
FILE *inFile;
FILE *outFile;
checkFiles(argc, argv,&inFile,&outFile);
int numOfStrings=0;
int sizeOfList=0;
char myString [MAX_STR_LEN];
int sortBy;
puts("Enter 0 for sort by NAME or 1 for sort by ID");
scanf("%d",&sortBy);
char** nameList;
int d;//TESTS
while(fgets (myString , MAX_STR_LEN , inFile) != NULL)
{
numOfStrings++;
if (sizeOfList==0)
sizeOfList++;
else
sizeOfList*=2;
if (numOfStrings==1)
{
nameList=realloc(nameList,sizeOfList*(sizeof(char**)));
if (nameList==NULL)
error("Can't allocate memory1");
nameList[0]=(char*)malloc(sizeof(char));
if (nameList[0]==NULL)
error("Can't allocate memory2");
strncpy(nameList[0],myString,sizeof(myString));
}
else
{
scanf("%d",&d);
nameList=realloc(nameList,sizeOfList*(sizeof(char**)));
scanf("%d",&d);
if (nameList==NULL)
error("Can't allocate memory3");
scanf("%d",&d);
nameList[numOfStrings]=(char*)malloc(sizeof(char));
if (nameList[numOfStrings]==NULL)
error("Can't allocate memory4");
scanf("%d",&d);
strncpy(nameList[numOfStrings],myString,sizeof(myString));
scanf("%d",&d);
}
}
nameList[0][0]='1'; why even this wont work?
int i=0;
scanf("%d",&d);
printf("%c",nameList[0][0]);
scanf("%d",&d);
for (;i<numOfStrings;i++)
fputs(nameList[i],outFile);
fclose(inFile);
fclose(outFile);
return 0;
}
/////////////////////////////FILE CHECK FUNCTION ////////////////////////////
void checkFiles(int argc, char *argv[],FILE * *in,FILE * *out )
{
if (argc!=3) error("Bad Number of parameters");
if (argc>1)
{
*in = fopen(argv[1], "r");
if (in==NULL)
error("Can't open input file");
}
else
error("No argv1");
if (argc>2)
{
*out = fopen(argv[2], "w");
if (out==NULL) error("Can't open output file");
}
else
error("No argv2");
}
///////////////////////////////////EXIT FUNCTION/////////////////////////////
void error(char *msg)
{
fprintf(stderr, "Error: %s\n", msg);
exit(EXIT_FAILURE);
}