我目前正在编写自己的网站,我试图确保当有人创建帐户时,用户名是唯一的。我正在用 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;
}
理想情况下,我的传入.txt 文件应如下所示:
名字=bla
描述=bla
用户名=bla
密码=bla
用户名=u1
用户名=u2
用户名=u3
...
现在我只能将传入的用户名与其他用户名进行比较,然后将数据复制回 newusers.txt。任何帮助,将不胜感激!
最佳答案
使用 system() 调用来调用 grep 二进制文件进行搜索,而不是用 C 语言编写搜索代码。
如下
//连接字符串以获取“grep filename username | cut -d'=' -f2”
到cmdstring中,然后
//读取内容
in=popen(cmdstring, "r");
if(in==NULL)
{
perror("Shell execution error");
exit(EXIT_FAILURE);
}
fgets(buf,3000,in)!=NULL)
这里 buf 包含新用户的名称,那么它已经存在。
否则他选择了独特的名字。
关于HTML 表单和 C - 检查唯一的用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36523185/