我目前正在处理的程序从文本文件中获取一些变量,并使用它们登录到安全摄像机中。我有一个配置文件,其中包含以下变量:
192.168.1.30
8000
admin
12345
./var/users/user/files_camera/我能够在控制台中阅读和打印它们:
fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Could not open file %s",filename);
return 0;
}
for(int i=0; i<variables; i++)
{
if(fgets(str, MAXCHAR, fp) != NULL)
{
if(i==0)
{
strcpy(ip, str);
}
if(i==1)
{
sscanf(str, "%d", &port);
}
if(i==2)
{
strcpy(user, str);
}
if(i==3)
{
strcpy(password, str);
}
if(i==4)
{
strcpy(directory, str);
}
}
}
fclose(fp);
printf("%s", ip);
printf("%d\n", port);
printf("%s", user);
printf("%s", password);
printf("%s", directory);问题是,程序在使用以下功能时工作:
lUserID = NET_DVR_Login_V30("192.168.1.30", 8000, "admin", "12345", &struDeviceInfo);但在使用:
lUserID = NET_DVR_Login_V30(ip, port, user, password, &struDeviceInfo);编译时没有错误,只是程序无法按预期工作:程序编译和执行,但相机返回一个登录错误,因为用户名和密码错误。这是变量的声明:
#define MAXCHAR 50
char ip[MAXCHAR];
int port;
char user[MAXCHAR];
char password[MAXCHAR];
char directory[MAXCHAR];我做错了什么?
发布于 2020-02-18 19:48:44
printf("%s", ip);
printf("%d\n", port);
printf("%s", user);
printf("%s", password);
printf("%s", directory);您注意到端口需要"%d\n“,而字符串参数不需要"\n”吗?这应该会给出这样的想法:那些参数已经以换行符结尾。所以你把错误的字符串传递给函数,不是"12345",而是"12345\n“。
发布于 2020-02-18 19:45:15
正如Alex所说,fget函数在末尾包含换行符,我没有记住这一点。这就是我为解决这个问题所做的:
char buffer[MAXCHAR];
strcpy(buffer, str);
strncpy(ip, buffer, strlen(buffer)-1);使用额外的变量读取每一行并删除每个变量末尾的\n字符。
现在起作用了!谢谢!
https://stackoverflow.com/questions/60288145
复制相似问题