gpt4 book ai didi

c - 如何使反斜杠字符不转义

转载 作者:行者123 更新时间:2023-12-04 04:51:12 26 4
gpt4 key购买 nike

我不知道标题是否正确解决了我的问题。所以,我就随它去吧。
这是问题所在,我必须输入一个包含大量反斜杠的文件路径(在 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]='\\';

职位 jp将更改为 \\ ,然后 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:\”进行测试)。

至少在带有 cygwin 的 Windows 7 上,这是我得到的。不需要任何转义,因为这是为您处理的。

关于c - 如何使反斜杠字符不转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17424386/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com