string parametres becoming empty

E

Erik

Hi, i'm trying to do this :

#include <stdlib.h>
#include <stdio.h>

#define FILE "/tmp/myfile"
#define USERS_LIST "/tmp/userslist"

int main() {
//open file
FILE *fp = fopen(FILE, "r");
char buf[512];

fgets(buf, sizeof(buf), fp);

char *username, *password, *pid;
pid = strtok(buf, ";");
username = strtok(NULL, ";");
password = strtok(NULL; ";");
if (SearchUser(username) != NULL) {
printf("user exists");
}
else {
if (RegisterUser(username, password) == 0) {
printf("registration successful");
}
}
}


/* Searches for user with name <username>.
Returns <password> if user is found.
Return NULL if no user with given username is found.*/
char *SearchUser(char *username) {

FILE *fp = fopen(USERS_LIST,"r");
while (feof(fp) == 0) {
char line[100];
char *buf = fgets(line, sizeof(line), fp);
char *iUsername = strtok(buf, ";");
char *iPassword = strtok(NULL, ";");

if (strcmp(iUsername, username) == 0) {
fclose(fp);
return iPassword;
}
}
fclose(fp);
return NULL;
}

/* Registers user with given <username> and <password>.
Returns 0 if registration successful.
Return -1 if registration failed.*/
int RegisterUser(char *username, char *password) {

FILE *fp = fopen(USERS_LIST, "a");
if ( fprintf(fp, "%s;%s;\n", username, password) < 0) {
fclose(fp);
return -1;
}
fclose(fp);
return 0;
}

But when I look with gdb inside SearchUser and RegisterUser functions I
notice that the string parameters I passed are empty... not NULL, (but
for example instead of <username> being "erik" it is "")
.... and in RegisterUser when I open the file, something has been
written but it is nonsense( like <username=erik password = mypwd,
inside the file i found /()/£GY;()"(G() ) .... I can't understand
where resides the problem...
thank you very much
 
E

Erik

yes, why ? the FILE define will disappear, as I will ask user for
filename, but for now it's like that...
 
?

=?ISO-8859-1?Q?=22Nils_O=2E_Sel=E5sdal=22?=

Erik said:
yes, why ? the FILE define will disappear, as I will ask user for
filename, but for now it's like that...
You have #define FILE "something"
Further down you have
FILE *fp = fopen(FILE, "r");

Think about what happens with the first FILE
token there, your code as posted does not compile.

Your code also lack error handling all over.
 
E

Erik

yeah, I know, but this is not the problem, I mean, this is a work in
progress code ( apart from the define that i have copied wrong from the
source, in fact it is FILE_PATH), the whole things works, the problem
is in the 2 functions / parameter passing... thanks
 
I

Ian Collins

Erik said:
yeah, I know, but this is not the problem, I mean, this is a work in
progress code ( apart from the define that i have copied wrong from the
source, in fact it is FILE_PATH), the whole things works, the problem
is in the 2 functions / parameter passing... thanks
Please quote context in your replies, see
<http://cfaj.freeshell.org/google/>

Your original code has at least one more syntax error, but should work
if that is corrected and the functions moved before main. Have you
checked your input files?

You are not changing the values passed to your functions, so you should
use const char* for your function parameters.
 
I

Ivan78

Hello Erik,
I have tried your code, it's right
I have changed only a few things
here is:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>


#define FILE1 "myfile"
#define USERS_LIST "userslist"


char *SearchUser(char *username);
int main()
{
//open file

char buf[512];
char *username, *password, *pid;


FILE *fp=fopen(FILE1, "r");



fgets(buf, sizeof(buf), fp);



pid = strtok(buf, ";");
username = strtok(NULL, ";");
password = strtok(NULL, ";");
if (SearchUser(username) != NULL) {
printf("user exists");
}
else {
if (RegisterUser(username, password) == 0) {
printf("registration successful");
}
}


}


/* Searches for user with name <username>.
Returns <password> if user is found.
Return NULL if no user with given username is found.*/
char *SearchUser(char *username) {

FILE *fp = fopen(USERS_LIST,"r");
while (feof(fp) == 0) {
char line[100];
char *buf = fgets(line, sizeof(line), fp);
char *iUsername = strtok(buf, ";");
char *iPassword = strtok(NULL, ";");


if (strcmp(iUsername, username) == 0) {
fclose(fp);
return iPassword;
}
}
fclose(fp);
return NULL;



}


/* Registers user with given <username> and <password>.
Returns 0 if registration successful.
Return -1 if registration failed.*/
int RegisterUser(char *username, char *password) {

FILE *fp = fopen(USERS_LIST, "a");
if ( fprintf(fp, "%s;%s;\n", username, password) < 0) {
fclose(fp);
return -1;
}
fclose(fp);
return 0;



}

ok?
 
?

=?ISO-8859-1?Q?=22Nils_O=2E_Sel=E5sdal=22?=

Erik said:
yeah, I know, but this is not the problem, I mean, this is a work in
progress code ( apart from the define that i have copied wrong from the
source, in fact it is FILE_PATH), the whole things works, the problem
is in the 2 functions / parameter passing... thanks

Very well. Then paste the actual code - and some samples
of the files in /tmp/ you are reading.
In the mean time, add error handling to your code too.
 
E

Erik

CLIENT

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>

//CHIDEDRE PER CLEAN
SCREEN____________________________________________________
#include <curses.h>

#define FIFO_FILE "/tmp/MYFIFO"

char *GetMessage(FILE *fifo);
void SendMessage(FILE *fifo, char *message);

int main(int argc, char *argv[])
{
/* stores informations about logged user and tells if a user is
logged.*/
char logUsername[50];
char logPassword[50];
int isLogged = 0;

/* program variables storing string commands and pointing to
FIFOs.*/
char menuChoice;
char command[512];
char *readbuffer;
FILE *fpRead;
FILE *fpWrite;

/* opens server fifo for sending commands to server.*/
if((fpWrite = fopen(FIFO_FILE, "w")) == NULL) {
perror("fopen");
exit(1);
}

/* get client PID.*/
char pid[20];
int intpid = getpid();
sprintf(pid,"%d", intpid);

printf("\nil pid è %s.\n", pid);

//makes client fifo for server replies.
char clientFifoPath[50] = "/tmp/fifo_";
strcat(clientFifoPath, pid);
mknod(clientFifoPath, S_IFIFO|0666, 0);

/* main program loop for commands sending/reply.*/
while(1) {

//clear();
printf("\nChe azione si vuole intraprendere ?\n\n1.Registare nuovo
utente.\n2.Effettuare il login.\n3.Effettuare il logoff.\n\n4.Cercare
un libro.\n5.Visualizzare lista dei libri disponibili.\n6.Prenotare un
libro.\n\n7.Uscire.\n\nScelta: ");
menuChoice = getchar();

switch(menuChoice) {

case '1': { /* USER REGISTRATION PROCEDURE*/

char username[50];
char password[50];
printf("\nInserire il nome utente: ");
scanf("%s", username);
printf("\nInserire la password: ");
scanf("%s", password);
sprintf(command,"%s;UREG;%s;%s;\n", pid, username, password);

SendMessage(fpWrite, command);
fpRead = fopen(clientFifoPath, "r");
readbuffer = GetMessage(fpRead);
if (strcmp(readbuffer, "UREGSUCC;\n") == 0) {
printf("\nRegistrazione avvenuta correttamente!\n");
}
else {
if (strcmp(readbuffer, "UREGFAIL;EXISTS;\n") == 0) {
printf("\nRegistrazione fallita! Utente già esistente!\n");
}
else {
printf("\nRegistrazione fallita! Malfunzionamento generico!
%s\n", readbuffer);
}
}
getchar();
fclose(fpRead);
break;
}
case '2': { /* LOGIN PROCEDURE*/

/* if an user is already logged block this new login
procedure.*/
if (isLogged) {
printf("\n\nUn utente è già loggato! Disconnetterlo se si
vuole fare un login diverso!\n");
break;
}
printf("\nInserire il nome utente: ");
scanf("%s", logUsername);
printf("\nInserire la password: ");
scanf("%s", logPassword);
sprintf(command,"%s;ULOGIN;%s;%s;\n", pid, logUsername,
logPassword);

SendMessage(fpWrite, command);
fpRead = fopen(clientFifoPath, "r");
readbuffer = GetMessage(fpRead);
if (strcmp(readbuffer,"ULOGINSUCC;\n")) {
printf("\n\nLogin avvenuto correttamente! Benvenuto, %s !\n",
logUsername);
isLogged = 1;
}
else {
printf("\nUsername o password errati: hai inserito %s - %s\n",
logUsername, logPassword);
}
getchar();
fclose(fpRead);

break;
}
case '3': { /* LOGOFF PROCEDURE*/
if (isLogged) {
sprintf(command,"%s;ULOGOFF;%s;%s;\n", pid, logUsername,
logPassword);
SendMessage(fpWrite, command);
fpRead = fopen(clientFifoPath, "r");
readbuffer = GetMessage(fpRead);
printf("\nServer replied: %s\n", readbuffer);
isLogged = 0;
fclose(fpRead);
}
else {
printf("\n\nPrima di effettuare il logoff è necessario essere
loggati!\n");
}
getchar();
break;
}
case '7': { /* QUIT PROCEDURE*/

/* if a user is logged require logoff before quitting.*/
if (isLogged) {
printf("\n\nPrima di uscire è necessario effettuare il
logoff!\n");
break;
}
/* closes open file pointers and quit program.*/
printf("\nBye!\n");
fclose(fpWrite);
/* deletes client fifo from computer.*/
unlink(clientFifoPath);
return 0;
break;
}
default: {
printf("\n\nScelta errata!\n\n");
getchar();
break;
}
}
}
}

void SendMessage(FILE *fifo, char *message) {

if (fprintf(fifo, "%s", message) < 0) {
printf("Error while writing message!");
}
fflush(fifo);
}

char *GetMessage(FILE *fifo) {
char buffer[512];
return fgets(buffer, sizeof(buffer), fifo);
}

void ProcessMessage(char *message) {

}

SERVER

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#define FIFO_FILE "/tmp/MYFIFO"
#define USERS_LIST "usersList.dat"
#define BIBLIOS_LIST "bibliosList.dat"

char *commands [10]= {"UREG","ULOGIN","ULOGOFF",
"UGETBOOKLIST","USEARCHBOOK","URESERVEBOOK","UGETRESBOOKLIST"};

void SendMessage(FILE *fifo, char *message);
char *GetMessage(FILE *fifo);

void ProcessMessage(char *message);

char *SearchUser(char *username);
int RegisterUser(char *username, char *password);

char *loggedUsers[100];
int loggedUsersNumber = 0;

char *activeBiblios[100];
int activeBibliosNumber = 0;


int main(void) {

/* file pointer for reception fifo and command buffer.*/
FILE *fp;
char *readbuffer;

/* Create the FIFO if it does not exist */
umask(0);
mknod(FIFO_FILE, S_IFIFO|0666, 0);

/* open reception FIFO.*/
int fd = open(FIFO_FILE, O_RDONLY);
/* open for WRONLY so when there are no writers, the read procedure
blocks and don't return EOF.*/
open(FIFO_FILE, O_WRONLY);
/* get file stream pointer to use with fgets.*/
fp = fdopen(fd, "r");

printf("Server started correctly, waiting for requests.\n");

while(1)
{
/* retrieve next message.*/
readbuffer = GetMessage(fp);
/* if a valid message was retrieved, process it.*/
if (readbuffer != NULL) {
ProcessMessage(readbuffer);
}
}

/* close reception FIFO.*/
fclose(fp);

return(0);
}

char *GetMessage(FILE *fifo) {
char buffer[512];
return fgets(buffer, sizeof(buffer), fifo);
}

void SendMessage(FILE *fifo, char *message) {
if (fprintf(fifo, "%s", message) < 0) {
printf("Error while writing message!");
}
fflush(fifo);
}

void ProcessMessage(char *message) {

char *command;
char *pid, *username, *password;
FILE *fifo;

//printf("\n1)Hi i'm in ProcessMessage");

//acquire PID in order to know what FIFO to open for reply.
pid = strtok(message, ";");
if (pid == NULL) {
printf("CLIENT PID NOT SENT, CANNOT ANSWER!");
return;
}
else {

/* obtain the name of client fifo for replies.*/
char nam[20] = "/tmp/fifo_";
strcat(nam, pid);

//QUI IL FILE VIENE CREATO QUINDI PROBLEMA TROVATO*********************
if ((fifo = fopen(nam, "w")) == NULL) {
printf("WRONG PID INSERTED, CANNOT ANSWER! %s", nam);
return;
}
//*********************************************************************

command = strtok(NULL, ";");
if (command == NULL) {
SendMessage(fifo, "CMDFAIL;BADFORM;\n");
fclose(fifo);
return;
}

int commandIndex = GetCommandIndex(command);

switch(commandIndex) {
case 0: { /* USER REGISTRATION PROCEDURE.*/

username = strtok(NULL, ";");
password = strtok(NULL, ";");
//FIRST TIME I DO STRTOK FOR PASSWORD, NULL IS RETURNED.... SECOND
TIME, CORRECT PASSWORD IS RETURNED... WHY ?????

if ((username == NULL) || (password == NULL)) {
SendMessage(fifo, "CMDFAIL;BADFORM;\n");
fclose(fifo);
return;
}

if (SearchUser(username) != NULL) {
SendMessage(fifo, "UREGFAIL;EXISTS;\n");
}
else {
if (RegisterUser(username, password) == 0) {
SendMessage(fifo, "UREGSUCC;\n");
}
else {
SendMessage(fifo, "UREGFAIL;\n");
}
}
fclose(fifo);
break;
}
case 1: { /* USER LOGIN PROCEDURE.*/

if (loggedUsersNumber < 100) {
/* fetches username and password.*/
username = strtok(NULL, ";");
password = strtok(NULL, ";");

if ((username == NULL) || (password == NULL)) {
/* the sent command was badly formatted.*/
SendMessage(fifo, "CMDFAIL;BADFORM;\n");
}
else {
/* search username and compare passwords.*/
char *registeredPassword = SearchUser(username);
if (registeredPassword == NULL) {
SendMessage(fifo, "ULOGINFAIL;NOUSER;\n");
}
else {
/* user found and right password.*/
if (strcmp(registeredPassword, password) == 0) {
SendMessage(fifo,"ULOGINSUCC;\n");
loggedUsersNumber++;
//update char array ?????
}
else {
/* user found but wrong password.*/
SendMessage(fifo, "ULOGINFAIL;WRONGPWD;\n");
}
}
}
}
else {
/* user limit achieved.*/
SendMessage(fifo, "ULOGINFAIL;NUSERSLIMIT;\n");
}

fclose(fifo);
break;
}
case 2: { /* USER LOGOFF PROCEDURE.*/
loggedUsersNumber--;
SendMessage(fifo,"ULOGOFF;\n");
fclose(fifo);
break;
}
default: { /* BADLY FORMATTED COMMAND.*/
SendMessage(fifo, "CMDFAIL;BADFORM;\n");
fclose(fifo);
break;
}
}
}
}

/* Matches the given string command with his numeric index.
Returns commandIndex if command is found.
Returns -1 if given command!feof(fp) doesn't exist.*/
int GetCommandIndex(char command []) {
int i = 0;
for (i = 0; i < 3; i++) {
if (strcmp(commands, command) == 0) {
//returns command index.
return i;
}
}
//command not found in commands list.
return -1;
}

/* Searches for user with name <username>.
Returns <password> if user is found.
Return NULL if no user with given username is found.*/
char *SearchUser(char *username) {

FILE *fp = fopen(USERS_LIST,"r");
while (feof(fp) == 0) {
char line[100];
char *buf = fgets(line, sizeof(line), fp);
char *iUsername = strtok(buf, ";");
char *iPassword = strtok(NULL, ";");

if (strcmp(iUsername, username) == 0) {
fclose(fp);
return iPassword;
}
}
fclose(fp);
return NULL;
}

/* Registers user with given <username> and <password>.
Returns 0 if registration successful.
Return -1 if registration failed.*/
int RegisterUser(char *username, char *password) {

FILE *fp = fopen(USERS_LIST, "a");
if ( fprintf(fp, "%s;%s;\n", username, password) < 0) {
fclose(fp);
return -1;
}
fclose(fp);
return 0;
}

SAMPLE OF usersList.dat

erik;mydogname;
kate;mypwd;
 
?

=?ISO-8859-1?Q?=22Nils_O=2E_Sel=E5sdal=22?=

[snip lot's of code]
char *GetMessage(FILE *fifo) {
char buffer[512];
return fgets(buffer, sizeof(buffer), fifo);
}

This function has a serious error in that it returns a pointer to a
local object that is gone when the function returns.
'buffer' here is what fgets returns, it doesn't exist
when GetMessage finishes.

If you're lucky, other people might point out some of the other
errors - which would have been much easier if the code had
readable indentation.
 
F

Flash Gordon

Nils said:
[snip lot's of code]
char *GetMessage(FILE *fifo) {
char buffer[512];
return fgets(buffer, sizeof(buffer), fifo);
}

This function has a serious error in that it returns a pointer to a
local object that is gone when the function returns.
'buffer' here is what fgets returns, it doesn't exist
when GetMessage finishes.

If you're lucky, other people might point out some of the other
errors - which would have been much easier if the code had
readable indentation.

Part of readable indenting being do *not* use tabs when posting. Replace
tabs with an appropriate number of spaces and indent by approximately 2
to 4 characters (depending on personal preferences) per level.
 
F

Fred Kleinschmidt

Ivan78 said:
Hello Erik,
I have tried your code, it's right
I have changed only a few things
here is:
/* Searches for user with name <username>.
Returns <password> if user is found.
Return NULL if no user with given username is found.*/
char *SearchUser(char *username) {

FILE *fp = fopen(USERS_LIST,"r");
while (feof(fp) == 0) {
char line[100];
char *buf = fgets(line, sizeof(line), fp);
char *iUsername = strtok(buf, ";");
char *iPassword = strtok(NULL, ";");


if (strcmp(iUsername, username) == 0) {
fclose(fp);
return iPassword;

This is very bad. If iPassword is not NULL, it is a pointer
to the first character in the local array 'line'. When this function
returns, 'line' ceases to exist. iPassword is no longer valid.
}
}
fclose(fp);
return NULL;
}
Definitely NOT ok.
 
J

Jordan Abel

Nils said:
[snip lot's of code]
char *GetMessage(FILE *fifo) {
char buffer[512];
return fgets(buffer, sizeof(buffer), fifo);
}

This function has a serious error in that it returns a pointer to a
local object that is gone when the function returns.
'buffer' here is what fgets returns, it doesn't exist
when GetMessage finishes.

If you're lucky, other people might point out some of the other
errors - which would have been much easier if the code had
readable indentation.

Part of readable indenting being do *not* use tabs when posting. Replace
tabs with an appropriate number of spaces and indent by approximately 2
to 4 characters (depending on personal preferences) per level.

Not 8? (my personal preference is 4, but 8 seems common)
 
F

Flash Gordon

Jordan said:
Not 8? (my personal preference is 4, but 8 seems common)

Tab stops are normally 8, but code should IMHO be indented a lot less
than that.

I was explicitly *not* saying to replace tabs by a number of spaces but
to indent with spaces and suggesting a reasonable range for the amount
of indentation.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc

Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

URGENT 1
Access violation reading location 0
A process take input from /proc/<pid>/fd/0, but won't process it 0
error 28
strtok 7
Help with EXT3 Filesystem work 1
write error 13
code 34

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top