作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我不知道标题是否正确解决了我的问题。所以,我就随它去吧。
这是问题所在,我必须输入一个包含大量反斜杠的文件路径(在 Windows 中)的字符数组,例如。 "C:\myfile.txt"并返回一个 C 风格文件路径的无符号字符数组,例如。 “C:\myfile.txt”。
我试着写一个函数。
unsigned char* parse_file_path(char *path);
{
unsigned char p[60];
int i,j;
int len = strlen(path);
for(i=0,j=0; i<len; i++, j++)
{
char ch = path[i];
if(ch==27)
{
p[j++]='\\';
p[j]='\\';
}
else
p[j] = path[i];
}
p[j]='\0';
return p;
}
parse_file_path("t\es\t \it)
,它返回
t←s it
.但是
parse_file_path("t\\es\\t \\it")
返回
t\es\t \it
.
最佳答案
如果我能提到您的代码的另一个问题。
您正在返回一个局部变量(您的 unsigned char p
)。这是未定义的行为。考虑声明一个 char* p
使用 malloc
动态分配内存然后返回 p
像你一样。例如。类似的东西:
char* p = malloc(60);
sizeof
使用
malloc
分配内存时但在这里我直接通过了 60,因为 C 标准保证
char
在所有平台上都是 1 个字节。
free
分配给
malloc
的内存.
p[j++]='\\';
p[j]='\\';
j
在
p
将更改为
\\
,然后
j
将递增,并在下一行对后续字符位置执行相同操作。你确定要这两个作业吗?
#include <stdio.h>
#include <string.h> /* for strlen */
#include <stdlib.h> /* for exit */
int main()
{
char path[60];
fgets(path, 60, stdin); /* get a maximum of 60 characters from the standard input and store them in path */
path[strlen(path) - 1] = '\0'; /* replace newline character with null terminator */
FILE* handle = fopen(path, "r");
if (!handle)
{
printf("There was a problem opening the file\n");
exit(1); /* file doesn't exist, let's quite with a status code of 1 */
}
printf("Should be good!\n");
/* work with the file */
fclose(handle);
return 0; /* all cool */
}
C:\cygwin\home\myaccount\main.c
关于c - 如何使反斜杠字符不转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17424386/
我是一名优秀的程序员,十分优秀!