I'm new to C language and want to read a string line by line, I made this function and want to know what do you think about it, can I rely on it a production environment ?
/**
* this function is not thread safe,
*/
char* strReadLine(char* text)
{
static char* text2;
static int start = 0;
static int length = 0;
int startTemp;
int lineLength = 0;
char* line = (char*) 0;
startTemp = start;
//not thread safe but at least make an error
if(start != 0 && text2 != text){
fprintf(stderr, "thread safe guerd fired by strReadLine function\n");
exit(EXIT_FAILURE);
}
text2 = text;
//thread safty end
//if new string
if(length == 0 || start == 0) length = strlen(text);
if(!length) return (char*) 0;//the string is 0 length
for(int x = startTemp; x < length; x++){
start++;
lineLength++;
if( text[x] == '\n'){
line = malloc(lineLength);//not lineLength+1 because I will remove the \n with \0
strncpy(line, text + (startTemp) , lineLength);
line[lineLength - 1] = '\0';
break;
}
}
//if end of file && not the last line
if(start == length && !line){
start = 0;
line = (char*) 0;
}
return line;
}
I have tested it with this text file
line1
line2
line3
line5
سطر6
line7
(line 4 is empty and line 6 contains non Latin characters stored in more than 1 byte in UTF-8 encoding)
like this, and it worked as expected
//char* input;this points to the string that is read from the file(I omitted the reading code)
char* line;
int x = 0;
while( (line = strReadLine(input)) ){
x++;
printf("%s\n",line);
if(x == 300){printf("emergency break\n");break;}
}
x = 0;
while( (line = strReadLine(input)) ){
x++;
printf("%s\n",line);
if(x == 300){printf("emergency break\n");break;}
}