Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6684824
  • 博文数量: 1159
  • 博客积分: 12444
  • 博客等级: 上将
  • 技术积分: 12570
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-13 21:34
文章分类

全部博文(1159)

文章存档

2016年(126)

2015年(350)

2014年(56)

2013年(91)

2012年(182)

2011年(193)

2010年(138)

2009年(23)

分类: C/C++

2016-01-16 17:33:54

[root@localhost 桌面]# gedit tmp.c

点击(此处)折叠或打开

  1. // C Language to Replace a specified Line in a Text File

  2. #include <stdio.h>

  3. int main(void)
  4. {
  5.     FILE *fileptr1, *fileptr2;
  6.     char filechar[40];
  7.     char c;
  8.     int delete_line, temp = 1;

  9.     printf("Enter file name: ");
  10.     scanf("%s", filechar);

  11.     fileptr1 = fopen(filechar, "r");
  12.     //print the contents of file .
  13.     while ((c = getc(fileptr1)) != EOF)
  14.     {
  15.         printf("%c", c);
  16.     }

  17.     printf("\nEnter line number to be deleted and replaced: ");
  18.     scanf("%d", &delete_line);

  19.     //take fileptr1 to start point.
  20.     rewind(fileptr1);
  21.     //open tempinterm.txt in write mode
  22.     fileptr2 = fopen("tempinterm.txt", "w");

  23.     while ((c = getc(fileptr1)) != EOF)
  24.     {
  25.         //till the line to be deleted comes,copy the content to other
  26.         if (temp != delete_line) {
  27.             putc(c, fileptr2);
  28.             while ((c = getc(fileptr1)) != '\n') putc(c, fileptr2);
  29.             putc('\n', fileptr2);
  30.             temp++;
  31.         } else {
  32.             while ((c = getc(fileptr1)) != '\n');
  33.             //read and skip the line ask for new text
  34.             printf("Enter new text: ");

  35.             //flush the input stream
  36.             fflush(stdin);
  37.             getchar();    //delete blank line

  38.             while ((c = getchar()) != '\n') putc(c, fileptr2);
  39.             //take the data from user and place it in new file
  40.             putc('\n', fileptr2);
  41.             temp++;
  42.         }
  43.     }

  44.     fclose(fileptr1);
  45.     fclose(fileptr2);
  46.     remove(filechar);
  47.     rename("tempinterm.txt", filechar);
  48.     fileptr1 = fopen(filechar, "r");
  49.     //reads the character from file
  50.     //until last character of file is encountered
  51.     while ((c = getc(fileptr1)) != EOF)
  52.     {
  53.         printf("%c", c);
  54.     }
  55.     fclose(fileptr1);
  56.     return 0;
  57. }
[root@localhost 桌面]# gcc tmp.c -o tmp

[root@localhost 桌面]# ./tmp
Enter file name: hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

Enter line number to be deleted and replaced: 1
Enter new text: asdf
asdf
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
[root@localhost 桌面]#


阅读(1062) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~