我目前正在编写自己的网站,并试图确保在有人注册帐户时,用户名是唯一的。我正在用C做后端(因为我不了解php / js),而且我一直在运行一个问题。现在,我在文件newuser.txt(此文件仅具有唯一的用户名)中获取环境变量,如下所示:
全名=测试
描述=测试
用户名=测试
密码=测试
我知道在newusers.txt文件的第3、7、11等行,我将获得用户名,因此我考虑将所有用户名添加到另一个文件(该文件还托管传入的数据),然后检查传入的数据用户名是唯一的,如果是,则我想将所有数据(例如全名,用户名等)添加到newusers.txt。这是我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[])
{
int currentLine = 1;
char fileLine[100];
int searchLine= 3;
char input[200];
int i=0;
int n = atoi(getenv("CONTENT_LENGTH"));
fgets(input,n+1,stdin); //get the input from the form
printf("Content-Type:text/html\n\n");
printf("<TITLE>Account Creation Query</TITLE>\n");
if (n == 0)
{
printf("<p> Error. Please try again.</p>");
}
FILE *f = fopen("newusers.txt", "ab");
FILE *g = fopen("incoming.txt", "ab");
if (f == NULL)
{
printf("<p> Error in opening the file. Check if the file exists</p>");
printf("<p><a href=\"../login.html\">Login Page</a></p>");
printf("<p><a href=\"../home.html\">Homepage</a></p>");
}
else
{
while(fgets(fileLine, 100, f)) /*searching for the usernames and adding them to the incoming.txt file */
{
if(searchLine == currentLine)
{
fputs(fileLine, g);
searchLine = searchLine + 4;
}
currentLine++;
}
char *token = strtok(input, "&"); /*tokenizing the incoming data and adding it to the incoming.txt file */
while(token!=NULL)
{
fputs(token, g);
fputs("\n", g);
token = strtok(NULL, "&");
}
}
printf("<p> Account created successfully. You can now login!</p>");
printf("<p><a href=\"../login.html\">Login Page</a></p>");
fclose(f);
fclose(g);
return 0;
}
理想情况下,此时我的incoming.txt文件应如下所示:
名字= bla
description = bla
用户名= bla
密码= bla
用户名= u1
用户名= u2
用户名= u3
...
现在,我将比较传入的用户名与其他用户名,然后将数据复制回newusers.txt中。任何帮助,将不胜感激!
最佳答案
我强烈建议您为该项目学习脚本语言。 PHP,Perl,Python,Ruby,Javascript…有很多选择,并且它们中的任何一个都比C更适合于Web编程。
话虽如此,这里您需要的是一个数据库。考虑使用SQLite或Berkeley DB;两者都很容易与C进行交互,并且比起使用平面文件(您在此处尝试这样做),它使您可以更轻松地执行查找和插入操作。