0
我試圖根據用戶輸入創建一個在行之間插入文本的函數。用戶必須指定行號和索引才能插入他的行。將文本插入到特定行中
目前,我已經設法插入行前的文本,但我不能將其插入到行「索引」。 有誰知道如何根據索引號插入? PS。我仍然是C編程的入門者。我知道文件打開和關閉的次數太多了!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void inserttext(void);
main()
{
inserttext();
}
void inserttext(void)
{
FILE *file1,*file2;
char *f = malloc(sizeof(char)), *t = malloc(sizeof(char));
int l,i,r,y,n,index,nl=0;
printf("Enter a text file name: ");
scanf("%s",f);
if (access(f,F_OK)!=-1)//if the text file exists
{
file1=fopen(f, "r+");
file2=fopen("f2.txt", "w+");
printf("\nThe file before editing:\n\n");
while((n=fgetc(file1))!=EOF)// to show the contents of the file before the edit
{
putchar(n);
}
fclose(file1);
fclose(file2);
if(access(f,W_OK)!=-1)//if the file has the write permission
{
file1=fopen(f, "r+");
file2=fopen("f2.txt", "w+");
printf("\n\nPlease enter your text: \n");
scanf(" %[^\n]s ",t);
printf("Specify the line number where you want to insert: ");
scanf("%d", &l);
printf("\nindex:\n");
scanf("%d", &index);
while((r=fgetc(file1))!=EOF)//copying file1 contents into file2 contents
{
fputc(r,file2);
if(r == '\n' && ++nl == l){
fprintf(file2, "%s ", t);//adding the inserted text
}
}
fclose(file1);
fclose(file2);
file1=fopen(f, "w+");
file2=fopen("f2.txt", "r");
while((y=fgetc(file2))!=EOF){
fputc(y,file1);
}
fclose(file2);
fclose(file1);
remove("f2.txt");
file1=fopen(f, "r");
printf("\n");
while((i=fgetc(file1))!=EOF)//showing the result after inserting
{
putchar(i);
}
fclose(file1);
free(f);
free(t);
}
else{
printf("\n%s text file does not have the Write Permission!", f);
free(f);
free(t);
return;
}
}else{
printf("file doesn't exits!\n");
}
}
'char * f = malloc(sizeof(char))'是否正確? – Subinoy
您只能閱讀索引,但不要檢查也不要使用它。你的意思是什麼?列號? – LeleDumbo
@Subinoy:很好。他可能很幸運不會寫入無效內存(但可能會覆蓋一些有效的內存)。 – LeleDumbo