Compare strings - file functions
#1

I want to know how many "GranaT3" I have in my file "name.txt"

Код:
new File:handle = fopen("name.txt", io_read), buf[128];
 
	if(handle)
	{
		while(fread(handle, buf))
		{
                     if(!strcmp(buf, "GranaT3", true))
                     {
                     printf("%s", buf);
                     }
		}  			
	}

	else
	{
		print("The file \"file.txt\" does not exists, or can't be opened.");
	}
But nothing prints (code does not work). What would be the right way ?.
Reply
#2

You're using "while" incorrectly.
PHP код:
while(fread(handlebuf))
{
            if(!
strcmp(buf"GranaT3"true))
            {
                
printf("%s"buf);
            }

Reply
#3

Quote:
Originally Posted by CmZxC
Посмотреть сообщение
You're using "while" incorrectly.
PHP код:
while(fread(handlebuf))
{
            if(!
strcmp(buf"GranaT3"true))
            {
                
printf("%s"buf);
            }

No, that's not the problem, I tested this and it's the same result (none).
Reply
#4

Where did you even paste your code? Is it even being called?

If not, place it in either main() or OnGameModeInit.
Reply
#5

It is a function.

The function is called in:

pawn Код:
public OnGameModeInit()
{
    file_a();

    return 1;
}
That's not the problem.
Reply
#6

pawn Код:
// ** INCLUDES

#include <a_samp>

// ** DEFINES

#define plural_singular(%0,%1,%2) ((%0) == 1) ? ((#%1)) : ((#%2))

// ** MAIN

main()
{
    print("Loaded \"count_text_in_file.amx\".");

    CountTextInFile("count_text_in_file.txt", "hello");
}

// ** CALLBACKS

public OnGameModeInit()
{
    return 1;
}

public OnGameModeExit()
{
    return 1;
}

// ** FUNCTIONS

stock CountTextInFile(file_name[], text[])
{
    new File:file = fopen(file_name, io_read);
    if(file)
    {
        new string[128], count, pos, last_pos, length = strlen(text);
        while(fread(file, string))
        {
            for(;;)
            {
                pos = strfind(string, text, false, last_pos);

                if(pos != -1)
                {
                    last_pos = pos + length;
                    count ++;
                }
                else
                {
                    pos = 0;
                    last_pos = 0;
                    break;
                }
            }
        }

        printf("Found \"%s\" %d %s in \"%s\".", text, count, plural_singular(count, "time", "times"), file_name);
    }
    else
    {
        printf("Couldn't open \"%s\".", file_name);
    }
    return 1;
}
Quote:
Originally Posted by count_text_in_file.txt
hello how are you

hey

hello hey hello bro hello

yo

yooooo hello

hey yo

hello bro
Quote:

Found "hello" 6 times in "count_text_in_file.txt".

Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)