Beginner: malloc and array of strings
I would like to read a conf file and put parameters of my configuration in some variables. But when I parse file and put parameters to array of strings (that I would like to use in rest of programm) and try to print those strings (for testing purposes) I have garbage...
I think that I have problem allocating memory for array of string and need your help understanding how things works .....
Here is the code that doesn't work:
-------------------------------------------------
Code:
#include <stdio.h>
#include <string.h>
#define MAXSTRING 256
#define comment '#'
#define conffile "backup.conf"
#define logfile "backup.log"
//////////////////////////////////////////////////////////////
////// Log file procedure ///////////////////////////////////
//////////////////////////////////////////////////////////////
void log_message(char * m_essage1,char * m_essage2)
{
FILE *f_ile;
f_ile=fopen(logfile,"w+");
if(f_ile==NULL)
{
printf("Error: can't open log file!\n");
exit(1);
}
time_t t=time(NULL);
char *t_ime=ctime(&t);
fprintf(f_ile,"%-s | %-s %-s\n",t_ime,m_essage1,m_essage2);
fclose(f_ile);
return 0;
}
/////////////////////////////////////////////
//////////// MAIN ///////////////////////////
/////////////////////////////////////////////
int main()
{
char _buff_in[MAXSTRING];
char **_param;
int str_nos=20; //No of strings you want to have
int str_len=256; //Maximum length of each string
_param=calloc( str_nos,sizeof(char *) );
if(_param == NULL )
{
log_message("Error: calloc _param.","");
exit(1);
}
int k;
for(k=0;k<str_nos;k++)
{
_param[k]=calloc( str_len,sizeof(char *) );
if(_param[k] == NULL )
{
log_message("Error: calloc _param[k].","");
exit(1);
}
}
FILE *fp;
if ( (fp = fopen(conffile, "r")) == NULL)
{
log_message( "Error: Opening backup.conf.\n","");
exit(1);
}
int i=0;
while (!feof(fp))
{
fgets(&_buff_in, MAXSTRING, fp );
if((strchr(&_buff_in,comment))==NULL)
{
sscanf(&_buff_in,"%*s %*s %256[^\n]c",&_param[i]);
printf("%s\n",&_param[i]);
i++;
}
}
fclose(fp);
int j;
puts("--------------------------");
for(j=0;j<i;j++)
{
printf("%s\n",&_param[j]);
free(_param[j]);
}
free(_param);
return 0;
}
--------------------------------------------
HERE IS MY CONF FILE:
--------------------------------------------
#OS = Linux
OS = Windows
#
#
NUMB_DIF_EXT = 15
#
#
#EXT = .trc
EXT = .log;.trc
#
#
#MULTIPLE_FILES = YES
MULTIPLE_FILES = NO
#
#
#ARCHIVE = .tar
ARCHIVE = .zip
#
#
#SOURCE = /usr/home/docs
SOURCE = C:\Documents and Settings\Default User\Desktop
#
#
#INCLUDE_SUBFOLDERS = NO
INCLUDE_SUBFOLDERS = YES
#
#
#DESTINATION = /usr/home/backup
DESTINATION = D:\docs\CodeBlocks\Backup
---------------------------------------------------