函数

strncpy()

  • 作用
    限制最大字符复制字符串,要比strcpy()更安全
  1. 参数
    (字符串指针,被复制的字符串指针,最大个数)

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<stdio.h>
#include<stdlib.h>//提供exit()原型
#include<string.h>//提供strcpy(),strcat()原型
#define LEN 40
char * s_gets(char * st, int n);
int main(int argc, char *argv[])
{
char name[LEN];
char file[LEN];
char ch;
int ct = 0;
FILE *in;
FILE *out;

printf("Please enter file name:");
s_gets(name, LEN);//会将换行符替换为'\0'
if((in = fopen(name, "r")) == NULL)
{
fprintf(stderr, "Could not open %s file", name);
exit(EXIT_FAILURE);
}
strncpy(file, name, LEN);//限制字符串不超过40
file[LEN - 4] = '\0';//超过40就截断
strcat(file, ".io");
if((out = fopen(file, "w")) == NULL)
{
fprintf(stderr, "Could not create output file");
exit(EXIT_FAILURE);
}
while((ch = getc(in)) != EOF)
{
ct++;
if(ct % 3 == 0)
putc(ch, out);
}
if(fclose(out) != 0 || fclose(in) != 0)
fprintf(stderr, "Error in closing file");

return 0;
}
char * s_gets(char * st, int n)
{
char * find;
char * ret_val;

ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n'); //查找换行符
if (find)
*find = '\0'; //替换为空字符
else
while (getchar() != '\n')
continue; //处理多余输入
}

return ret_val;
}