修改用户输入的文件路径以扫描C中同一目录中的文件
Modifying user-input file path to scan files in the same directory in C
我正在开发一个用户输入文件路径的程序,然后将带有文件名的附加字符串连接到该程序。我将把它用于同一目录中的多个文件。
我正在使用 printf 语句只是为了查看操作是否有效,但是当显示输出时 文件路径被打印两次 ,然后在最后添加文件名。例如
输入文件路径是C:\Documents\
输出出来了C:\Documents\C:\Documents\HR_1.txt
如何纠正?
相关代码如下
int main()
{
char folder[50]="";
printf("Please type file location\n");
printf("An example of file location is C:\Documents\projects\[Folder]\");
printf("\n");
scanf("%s",folder);
printf(folder);
/*Clearing Heart rate file names, opening file*/
FILE*HR1=NULL;
printf(strcat(folder,"HR_1.txt"));
}
}
您将对 printf
的两次调用的输出混合在一起。
printf
的第一个参数应该总是 是字符串文字,而不是变量。这可以防止意外的转义序列被解释,并允许您在格式中添加换行符。
因为您对 printf
的两次调用,一次在追加之前,一次在追加之后,不包括换行符,它们出现在同一行。
所以改变这个:
printf(folder);
...
printf(strcat(folder,"HR_1.txt"));
收件人:
printf("%s\n", folder);
...
printf("%s\n", strcat(folder,"HR_1.txt"));
输出:
C:\Documents\
C:\Documents\HR_1.txt
我正在开发一个用户输入文件路径的程序,然后将带有文件名的附加字符串连接到该程序。我将把它用于同一目录中的多个文件。 我正在使用 printf 语句只是为了查看操作是否有效,但是当显示输出时 文件路径被打印两次 ,然后在最后添加文件名。例如
输入文件路径是C:\Documents\
输出出来了C:\Documents\C:\Documents\HR_1.txt
如何纠正?
相关代码如下
int main()
{
char folder[50]="";
printf("Please type file location\n");
printf("An example of file location is C:\Documents\projects\[Folder]\");
printf("\n");
scanf("%s",folder);
printf(folder);
/*Clearing Heart rate file names, opening file*/
FILE*HR1=NULL;
printf(strcat(folder,"HR_1.txt"));
}
}
您将对 printf
的两次调用的输出混合在一起。
printf
的第一个参数应该总是 是字符串文字,而不是变量。这可以防止意外的转义序列被解释,并允许您在格式中添加换行符。
因为您对 printf
的两次调用,一次在追加之前,一次在追加之后,不包括换行符,它们出现在同一行。
所以改变这个:
printf(folder);
...
printf(strcat(folder,"HR_1.txt"));
收件人:
printf("%s\n", folder);
...
printf("%s\n", strcat(folder,"HR_1.txt"));
输出:
C:\Documents\
C:\Documents\HR_1.txt