468,268 Members | 1,699 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,268 developers. It's quick & easy.

string parametres becoming empty

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

May 15 '06 #1
14 1576
Erik wrote:
Hi, i'm trying to do this :

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

#define FILE "/tmp/myfile"


Are you sure you want to do that????

--
Ian Collins.
May 15 '06 #2
yes, why ? the FILE define will disappear, as I will ask user for
filename, but for now it's like that...

May 15 '06 #3
Erik wrote:
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.
May 15 '06 #4
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

May 15 '06 #5
Erik wrote:
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.

--
Ian Collins.
May 15 '06 #6
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?

May 15 '06 #7
ok! thank you very much!

May 15 '06 #8
Erik wrote:
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.
May 15 '06 #9
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","UGETR ESBOOKLIST"};

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[i], 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;

----------------------------
That's all.... there are strings in italian, as the interface should be
in italian, but that doesn't affect code.... thanks

May 15 '06 #10
[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.
May 15 '06 #11
Nils O. Selåsdal wrote:
[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.
--
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
May 15 '06 #12

"Ivan78" <iv*****@cheapnet.it> wrote in message
news:11********************@y43g2000cwc.googlegrou ps.com...
Hello Erik,
I have tried your code, it's right
I have changed only a few things
here is: <snip> /* 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;
} <snip> ok?

Definitely NOT ok.
--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project
May 15 '06 #13
On 2006-05-15, Flash Gordon <sp**@flash-gordon.me.uk> wrote:
Nils O. Selåsdal wrote:
[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)
May 16 '06 #14
Jordan Abel wrote:
On 2006-05-15, Flash Gordon <sp**@flash-gordon.me.uk> wrote:


<snip>
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)


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
May 16 '06 #15

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

8 posts views Thread by David Thielen | last post: by
11 posts views Thread by Dan Bass | last post: by
8 posts views Thread by Peter Merwood | last post: by
4 posts views Thread by deancarstens | last post: by
26 posts views Thread by Neville Lang | last post: by
35 posts views Thread by Smithers | last post: by
21 posts views Thread by Sami | last post: by
reply views Thread by kermitthefrogpy | last post: by
reply views Thread by zattat | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.