新编辑: 基本上我提供了一个不正确的例子。在我的实际应用程序中,字符串当然不会总是“C:/Users/Familjen-Styren/Documents/V\u00E5gformer/20140104-0002/text.txt”。相反,我将在 java 中有一个输入窗口,然后我会将unicode 字符“转义”为通用字符名称。然后它将在 C中“未转义” (我这样做是为了避免将多字节字符从 java 传递到 c 时出现问题)。所以这里有一个例子,我实际上要求用户输入一个字符串(文件名):
#include <stdio.h>
#include <string.h>
int func(const char *fname);
int main()
{
char src[100];
scanf("%s", &src);
printf("%s\n", src);
int exists = func((const char*) src);
printf("Does the file exist? %d\n", exists);
return exists;
}
int func(const char *fname)
{
FILE *file;
if (file = fopen(fname, "r"))
{
fclose(file);
return 1;
}
return 0;
}
现在它会认为通用字符名称只是实际文件名的一部分。那么如何“取消转义”输入中包含的通用字符名称?
第一次编辑: 所以我像这样编译这个例子:“gcc -std=c99 read.c”,其中“read.c”是我的源文件。我需要 -std=c99 参数,因为我使用前缀 '\u' 作为我的通用字符名称。如果我将它更改为 '\x' 它工作正常,我可以删除 -std=c99 参数。但在我的实际应用程序中,输入不会使用前缀“\x”,而是使用前缀“\u”。那么我该如何解决这个问题呢?
这段代码给出了想要的结果,但对于我的实际应用程序,我不能真正使用 '\x':
#include <stdio.h>
#include <string.h>
int func(const char *fname);
int main()
{
char *src = "C:/Users/Familjen-Styren/Documents/V\x00E5gformer/20140104-0002/text.txt";
int exists = func((const char*) src);
printf("Does the file exist? %d\n", exists);
return exists;
}
int func(const char *fname)
{
FILE *file;
if (file = fopen(fname, "r"))
{
fclose(file);
return 1;
}
return 0;
}
原文: 我找到了一些如何在其他编程语言(如javascript )中执行此操作的示例,但我找不到任何有关如何在 C 中执行此操作的示例。这是一个产生相同错误的示例代码:
#include <stdio.h>
#include <string.h>
int func(const char *fname);
int main()
{
char *src = "C:/Users/Familjen-Styren/Documents/V\u00E5gformer/20140104-0002/text.txt";
int len = strlen(src); /* This returns 68. */
char fname[len];
sprintf(fname,"%s", src);
int exists = func((const char*) src);
printf("%s\n", fname);
printf("Does the file exist? %d\n", exists); /* Outputs 'Does the file exist? 0' which means it doesn't exist. */
return exists;
}
int func(const char *fname)
{
FILE *file;
if (file = fopen(fname, "r"))
{
fclose(file);
return 1;
}
return 0;
}
如果我改为使用没有通用字符名称的相同字符串:
#include <stdio.h>
#include <string.h>
int func(const char *fname);
int main()
{
char *src = "C:/Users/Familjen-Styren/Documents/Vågformer/20140104-0002/text.txt";
int exists = func((const char*) src);
printf("Does the file exist? %d\n", exists); /* Outputs 'Does the file exist? 1' which means it does exist. */
return exists;
}
int func(const char *fname)
{
FILE *file;
if (file = fopen(fname, "r"))
{
fclose(file);
return 1;
}
return 0;
}
它会输出'文件是否存在?1'。这意味着它确实存在。但问题是我需要能够处理通用字符。那么如何对包含通用字符名称的字符串进行转义呢?
提前致谢。