Code:
#define LINE_MAX 1024
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
char *find_param( char *buffer, int buffersize, const char *param_name,
FILE *stream )
{
char *hash;
char *value;
char *equal;
// reset stream to beginning of file (with SEEK_SET + 0 offset)
fseek( stream, 0, SEEK_SET);
while( ( fgets( buffer, buffersize, stream ) ) != (char *)0 ){
// get rid of all comments, preceeded by a # symbol
hash = index(buffer,'#');
if( hash != NULL ){
*hash = '\0';
}
// check if we find '=' in current line in buffer
// if there isn't one in this line, go to next line
equal = index(buffer,'=');
if( equal == NULL )
continue;
// set start of value (pointer arithmetic) in case there is a match
value = equal + 1;
// cut off string at '=' for string comparison
*equal = '\0';
// compare cut off string in buffer to param_name sought
// if they agree, return the pointer
if( strcmp( buffer, param_name) == 0 ) {
return(value);
}
}
return(NULL);
}
char *get_str_param(const char *param_name, FILE *stream )
{
char *buffer;
char *value_pointer;
char *equal;
int i;
// set buffer size for input file lines
if( ( buffer = (char *) calloc( LINE_MAX, sizeof(char))) == NULL ){
fprintf(stderr,"error in get_str_param: calloc failed");
exit(1);
}
// find pointer to parameter value, (pointer to char array)
if( ( value_pointer = find_param( buffer, LINE_MAX, param_name, stream ) )
== NULL ){
fprintf(stderr,"error in get_str_param: ");
fprintf(stderr,"Didn't find parameter %s in input file\n", param_name );
exit(1);
}
free(buffer);
return(value_pointer);
}
int main()
{
char *param;
char input_file_name[100] = "input_test.txt";
FILE *input;
input = fopen(input_file_name,"r");
if (input == NULL)
{
printf("file open failed\n");
abort();
}
param = get_str_param("source",input);
printf("%s",param);
}
The functions above are part of a larger code, I just wrote main here to test a new one, that is supposed to read a string from an input file of format:
parameter=string
The code is supposed to go through the file, find parameter, and return the string that comes after the equal sign.
It works! However, for some reason when it prints out, there is a newline being printed (or possible just lots of whitespace, I can't tell. To get rid of it, I tried:
Code:
equal = index(value_pointer,'\n');
if( equal != NULL )
{
equal = '\0';
}
in get_str_param just before freeing buffer, but it makes no difference. Could someone point me in the direction of my mysterious newline?
Thanks