我需要一个程序,可以将多个帐户存储在不同的文件中。这就是我到目前为止所做的,但由于某种原因(“test”+ userName +“.txt”,“a”);不起作用。感谢您的宝贵时间!
int main() {
char choice[10];
printf("create accout (1)");
printf("\nlogin to accout (2)\n");
scanf("%s", &choice);
getchar();
if (strcmp(choice, "1") == 0)
{
char userName[1000];
FILE *myFile;
myFile = fopen("test" + userName + ".txt", "a");
if (myFile == NULL)
{
printf("file does not exist");
}
else
{
printf("Enter your username: ");
gets(userName);
fprintf(myFile, "%s", userName);
fclose(myFile);
}
}
最佳答案
在 C 语言中,“字符串”(char *
) 实际上只是指向以零结尾的 char
数组的第一个元素的指针,解释为 由库函数作为字符串。
您不能简单地将此类指针与 +
连接起来,就像在其他一些具有显式字符串类型的语言中一样。
要组装字符串,您必须使用类似 strcat()
的方法来创建适当大小的缓冲区:
char buffer[MAX_PATH];
...
strcpy(buffer, "test");
strcat(buffer, userName);
strcat(buffer, ".txt");
myFile = fopen(buffer, "a");
或者,您可以使用sprintf()
:
int res = sprintf(buffer, "test%s.txt", userName);
if (res > 0)
{
myFile = fopen(buffer, "a");
等等...
关于在C中创建不同名称的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48035128/