linux下将终端的输入存入文件中

代码很简单:

  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行的代码了。

下面代码将上边存储的文本全部读取出来:

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4
  5 #define MAX_LINE 1024
  6
  7 int main(int argc, char **argv)
  8 {
  9     char buf[MAX_LINE];
 10     FILE* fd = fopen("sam1", "r");
 11     while(fgets(buf, MAX_LINE, fd)  != NULL){
 12         int len = strlen(buf);
 13         buf[len - 1] = '\0';
 14         printf("%s %d \n", buf, len - 1);
 15     }
 16
 17     return 0;
 18 }

  同学们,请自行尝试,有问题请留言。

  改造代码如下:

readFile.c  
1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4
  5 #define MAX_LINE 1024
  6
  7 int main(int argc, char **argv)
  8 {
  9     if(argc < 2){
 10         printf("Error!\n");
 11     }
 12     char buf[MAX_LINE];
 13     FILE* fd = fopen(*(argv + 1), "r");
 14     while(fgets(buf, MAX_LINE, fd)  != NULL){
 15         int len = strlen(buf);
 16         buf[len - 1] = '\0';
 17         //printf("%s %d \n", buf, len - 1);
 18         printf("%s\n", buf);
 19     }
 20
 21     return 0;
 22 }
writeFile.c
  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     if(argc < 2){
 10         printf("Error!\n");
 11     }
 12     int fd;
 13     fd = open(*(argv + 1), O_RDWR|O_CREAT|O_APPEND, S_IRWXU);
 14     printf("please input:");
 15     char *tmpc = (char *)malloc(sizeof(char));
 16     //scanf("%s", tmpc);
 17     int tmpp = gets(tmpc);
 18     int size = strlen(tmpc);
 19     printf("you input: %s and size:%d\n", tmpc, size);
 20     write(fd, tmpc, strlen(tmpc));
 21     write(fd, "\n", 1);
 22
 23     int tmp = close(fd);
 24
 25     return 0;
 26 }

  改造后的代码,需要指出需要使用的文件名称而已,更加具有普遍性。

 

posted @ 2019-12-18 11:09  叕叒双又  阅读(742)  评论(0编辑  收藏  举报