Skip empty lines - file functions -
dusk - 11.02.2014
Hey, I was wanted to read some data from a file when the server starts.
The file contains empty lines. I thought I will just get an empty string, but "isnull" function says it isn't. I printed out the string as an int and got 13, which is something called "carriage return"...
My question: how do I detect these empty lines?
P.S. The file contains just some data like coordinates and some text. I only load it when my mode starts and speed is not the problem. Also, I don't need key-value, so don't suggest using other file reading/writing systems.
Re: Skip empty lines - file functions -
PowerPC603 - 11.02.2014
First read your line and store it into a string, then use
pawn Код:
stock StripNewLine(string[])
{
new len = strlen(string);
if (string[0]==0) return ;
if ((string[len - 1] == '\n') || (string[len - 1] == '\r')) {
string[len - 1] = 0;
if (string[0]==0) return ;
if ((string[len - 2] == '\n') || (string[len - 2] == '\r')) string[len - 2] = 0;
}
}
From the include file "dutils.inc" (it's included in the server package) to strip newline-characters from your string.
After that you can use "strlen" to check if you have read an empty line.
Re: Skip empty lines - file functions -
dusk - 11.02.2014
Thank you! Exactly what I needed.
Re: Skip empty lines - file functions -
ColeMiner - 11.02.2014
Another way to check if a line is mostly empty is:
"\r" and "\n" are both used in various combinations to mean "new line". If you were to do:
pawn Код:
fwrite(fhnd, "hello");
fwrite(fhnd, "there");
The file would look like:
Because no new line characters have been inserted (they must be explicit for file functions, unlike "print" and "printf"):
pawn Код:
fwrite(fhnd, "hello");
fwrite(fhnd, "\r\n");
fwrite(fhnd, "there");
Gives:
Reading the first line back in again will give the string "hello\r\n". Similarly a "blank" line isn't truly blank because it needs these new line characters, so becomes just "\r\n". Of course, neither PowerPC603's method nor my method will regard " \r\n" as a blank line, despite the fact that it only contains whitespace. An alternate function to take that in to account would be:
pawn Код:
bool:IsBlankLine(const str[])
{
new
i = 0;
while ('\0' < str[i] <= ' ') ++i;
return !str[i];
}
A possibly even more useful function would be:
pawn Код:
bool:GetLine(const str[], &i)
{
i = 0;
while ('\0' < str[i] <= ' ') ++i;
return bool:str[i];
}
Then you can do:
pawn Код:
if (GetLine(str, pos))
{
// The useful text starts at position "pos".
}