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 14 1803
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.
yes, why ? the FILE define will disappear, as I will ask user for
filename, but for now it's like that...
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.
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
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.
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?
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.
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
[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.
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
"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
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)
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: DraguVaso |
last post by:
Hi,
To get faster performance of my DataGrid during scrolling I wanted to build
a timer in the Paint-event that waited some milli-seconds to Paint and
cancelled the method in case it received a...
|
by: David Thielen |
last post by:
Hi;
I have a string that is an xml file. It starts with <?xml
encoding='utf-8'... and it has the utf-8 2-byte sequences as 2 chars. How do
I get that into an XPathDocument where the 2-char...
|
by: Dan Bass |
last post by:
which one do you use and why?
MyString == null || MyString == ""
vs
MyString == null || MyString.Length == 0
|
by: Peter Merwood |
last post by:
I'm using some sample code from MSDN. The code includes the following
statement:
Dim content as = .Empty
I'm not familiar with the use of the square brackets. Can someone please
explain to...
|
by: deancarstens |
last post by:
Hi,
This is a tougher one, but I'm quite sure someone will have a solution
for this. Of course, a last minute thing thrown at me by my boss.
I have a unique identifier consisting of regions,...
|
by: Neville Lang |
last post by:
Hi all,
I am having a memory blank at the moment. I have been writing in C# for a
number of years and now need to do something in VB.NET, so forgive me such a
primitive question.
In C#, I...
|
by: anonieko |
last post by:
In the past I always used "" everywhere for empty string in my code
without a problem.
Now, do you think I should use String.Empty instead of "" (at all
times) ?
Let me know your thoughts.
|
by: Smithers |
last post by:
I have been told that it is a good idea to *always* declare string variables
with a default value of string.Empty - for cases where an initial value is
not known... like this:
string myString =...
|
by: Sami |
last post by:
string = "" or string = string.Empty?
should is the proper way?
Sami
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM).
In this month's session, the creator of the excellent VBE...
|
by: MeoLessi9 |
last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
|
by: DolphinDB |
last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation.
Take...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: marcoviolo |
last post by:
Dear all,
I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
| |