[root@localhost 桌面]# gedit tmp.c
[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 桌面]#
阅读(101) | 评论(0) | 转发(0) |
<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
点击(此处)折叠或打开
- // C Language to Replace a specified Line in a Text File
-
- #include <stdio.h>
-
- int main(void)
- {
- FILE *fileptr1, *fileptr2;
- char filechar[40];
- char c;
- int delete_line, temp = 1;
-
- printf("Enter file name: ");
- scanf("%s", filechar);
-
- fileptr1 = fopen(filechar, "r");
- //print the contents of file .
- while ((c = getc(fileptr1)) != EOF)
- {
- printf("%c", c);
- }
-
- printf("\nEnter line number to be deleted and replaced: ");
- scanf("%d", &delete_line);
-
- //take fileptr1 to start point.
- rewind(fileptr1);
- //open tempinterm.txt in write mode
- fileptr2 = fopen("tempinterm.txt", "w");
-
- while ((c = getc(fileptr1)) != EOF)
- {
- //till the line to be deleted comes,copy the content to other
- if (temp != delete_line) {
- putc(c, fileptr2);
- while ((c = getc(fileptr1)) != '\n') putc(c, fileptr2);
- putc('\n', fileptr2);
- temp++;
- } else {
- while ((c = getc(fileptr1)) != '\n');
- //read and skip the line ask for new text
- printf("Enter new text: ");
-
- //flush the input stream
- fflush(stdin);
- getchar(); //delete blank line
-
- while ((c = getchar()) != '\n') putc(c, fileptr2);
- //take the data from user and place it in new file
- putc('\n', fileptr2);
- temp++;
- }
- }
-
- fclose(fileptr1);
- fclose(fileptr2);
- remove(filechar);
- rename("tempinterm.txt", filechar);
- fileptr1 = fopen(filechar, "r");
- //reads the character from file
- //until last character of file is encountered
- while ((c = getc(fileptr1)) != EOF)
- {
- printf("%c", c);
- }
- fclose(fileptr1);
- return 0;
- }
[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 桌面]#
上一篇:C language——read ip address in linux
下一篇:C language——to Replace a specified Line in a Text File—V2
相关热门文章
给主人留下些什么吧!~~
评论热议