[root@localhost 桌面]# gedit tmp.c
-
// 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 桌面]# 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) |