strcat()函数常见问题

  strcat(char *_Destination,const char *_Source)函数的功能是将后一个字符串粘贴到前一个字符串的末尾

原型

  char *strcat(char *_Destination,const char *_Source)

常见错误

  strcat函数常见的错误就是数组越界,即两个字符串连接后,长度超过第一个字符串数组定义的长度,导致越界

example1:
 1 void charWrite() {
 2     FILE *file;
 3     char type[4] = "wt+";
 4     char path[30] = "C:/Users/Fahy/Desktop/";  //数组总长度为30个字符,初始化存入22个字符
 5     char filename[20],ch;
 6     scanf("%s", filename);    //如果超过8个字符,strcat将两个字符串结合时,就会越界
 7     ch = getchar();
 8     ch = getchar();
 9     strcat(path, filename);
10     if (!(file = fopen(path, type))) {
11         printf("Can't open this file \"%s\"", path);
12         system("pause");
13     }
14     else {
15         while (ch != EOF)
16         {
17             fputc(ch, file);
18             ch = getchar();
19         }
20     }
21     fclose(file);
22 }

解决方法

  别无他法,只能将第一个参数定义长点。

你可能感兴趣的:(strcat()函数常见问题)