Reading from a file.
#1

Hello!

I have a question, how can I read from a file.
For example, in a file I have:

pawn Code:
Question = 12345
And, I want a function like:

pawn Code:
Read(filename[], text[]
Something like:

pawn Code:
new file[50];
format(file, ........................);
Add(file, "Question", 12345);
Read(file, Question);
And this function should return me 12345.

I tried, but I don't know how to continue.

pawn Code:
stock h_Read(filename[], text[])
{
    new string[50];
    if(!fexist(filename)) return false;
    new File:file = fopen(filename, io_read);
    while(fread(file, string))
    {
    }
    return false;
}
I looked into dini, but cannot understand what Dracoblue did.
+ Rep!
Reply
#2

pawn Code:
stock file_get_contents(filename[]) {
   
      new string[100];
      if(fexist(filename)) {
           new File:file = fopen(filename, io_read);
           fread(file, string);
           fclose(file);
           return string;
      }

      else return -1;

      return 1;
}
Returns -1 if the file doesn't exist.
Reply
#3

Quote:
Originally Posted by Abagail
View Post
pawn Code:
stock file_get_contents(filename[]) {
   
      new string[100];
      if(fexist(filename)) {
           new File:file = fopen(filename, io_read);
           fread(file, string);
           fclose(file);
           return string;
      }

      else return -1;

      return 1;
}
Returns -1 if the file doesn't exist.
And how could I get string only from specified text?

pawn Code:
Read(filename[], text[])
Question like:

pawn Code:
Add(file, "Question", 123456789);
Get only from 'Question', then should print: 123456789.
Reply
#4

You could basically copy dini_Get if you want that
Reply
#5

You can use common string functions such as strdel, strpos, etc.

For instance,

pawn Code:
stock get_question_answer()
{
     new string[64] = file_get_contents("file.cfg");
     if(strfind(string, "Question") != -1)
     {
         strmid(string, strpos(string, strfind(string, "Question"), strfind(string, "Question"+MAX_SIZE), sizeof(string));
     }

     return string;
}
This would get everything after "Question" and extract it into the string. You'll need to specify a MAX_SIZE where it will stop extracting the string at.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)