2015-01-21 41 views
-2

我正在从磁盘加载文本文件到我的C应用程序。一切正常,但文本包含多个转义字符,如\ r \ n和加载文本后,我想保留这些字符的计数,并相应地显示。C从文件加载文本,打印转义字符

这时如果我使用的字符串的printf,它表明我:

你好\ nMan \ n

这样做的有快捷方式?

+1

这很奇怪。请提供您的代码 – maxpovver 2015-01-21 07:14:39

+1

向我们展示您的代码的相关部分(您如何阅读和打印文件的内容)以及文本文件的内容 – 2015-01-21 07:20:26

+0

因此,该文件实际上包含字符串的转义版本,并且您希望例如,换行符是真正的新行? – 2015-01-21 07:30:40

回答

1

似乎有不被此标准的功能,但你可以滚你自己:

#include <stdlib.h> 
#include <stdio.h> 

/* 
*  Converts simple C-style escape sequences. Treats single-letter 
*  escapes (\t, \n etc.) only. Does not treat \0 and the octal and 
*  hexadecimal escapes (\033, \x, \u). 
* 
*  Overwrites the string and returns the length of the unescaped 
*  string. 
*/ 
int unescape(char *str) 
{ 
    static const char escape[256] = { 
     ['a'] = '\a',  ['b'] = '\b',  ['f'] = '\f', 
     ['n'] = '\n',  ['r'] = '\r',  ['t'] = '\t', 
     ['v'] = '\v',  ['\\'] = '\\',  ['\''] = '\'', 
     ['"'] = '\"',  ['?'] = '\?', 
    }; 

    char *p = str;  /* Pointer to original string */ 
    char *q = str;  /* Pointer to new string; q <= p */ 

    while (*p) { 
     int c = *(unsigned char*) p++; 

     if (c == '\\') { 
      c = *(unsigned char*) p++; 
      if (c == '\0') break; 
      if (escape[c]) c = escape[c]; 
     } 

     *q++ = c;  
    } 
    *q = '\0'; 

    return q - str; 
} 

int main() 
{ 
    char str[] = "\\\"Hello ->\\t\\\\Man\\\"\\n"; 

    printf("'%s'\n", str); 
    unescape(str); 
    printf("'%s'\n", str); 

    return 0; 
} 

此功能取消转义到位的字符串。这是安全的,因为非转义字符串不能比原始字符串长。 (另一方面,这可能不是一个好主意,因为相同的char缓冲区用于转义字符串和非转义字符串,并且您必须记住它保存的是哪一个。)

此函数不会将数字序列为八进制和十六进制符号。有more complete implementations左右,但它们通常是某些库的一部分,并依赖于其他模块,通常用于动态字符串。

也有类似的functions for escaping一个字符串,当然。