代码很简单:

  1 #include <stdlib.h>
  2 #include <fcntl.h>
  3 #include <stdio.h>
  4 #include <unistd.h>
  5 #include <string.h>
  6
  7 int main(int argc, char **argv)
  8 {
  9     int fd;
 10     fd = open("sam1", O_RDWR|O_CREAT|O_APPEND, S_IRWXU);
 11     printf("please input:");
 12     char *tmpc = (char *)malloc(sizeof(char));
 13     //scanf("%s", tmpc);
 14     scanf("%[^\n]", tmpc);
 15     int size = strlen(tmpc);
 16     printf("you input: %s and size:%d\n", tmpc, size);
 17     write(fd, tmpc, strlen(tmpc));
 18     write(fd, "\n", 1);
 19
 20     int tmp = close(fd);
 21
 22     return 0;
 23 }

  这里唯一的一个坑就是:第13行的scanf函数不能接受有空格的字符串,让我郁闷了一上午,终于搞定了。原来,是sanf()函数在接收字符串时,遇到空格就会停止接收。可以使用gets()函数代替,但也可以用以下方式解决:

      这里主要介绍一个参数,%[ ],这个参数的意义是读入一个字符集合。[ ]是个集合的标志,因此%[ ]特指读入此集合所限定的那些字符,比如%[A-Z]是输入大写字母,一旦遇到不在此集合的字符便停止。如果集合的第一个字符是“^”,这说明读取不在“^“后面集合的字符,即遇到”^“后面集合的字符便停止。此时读入的字符串是可以含有空格的。(\n 表示换行符)

  因此形成了第14行的代码了。

12-21 14:11
查看更多