【发布时间】:2020-09-05 17:22:47
【问题描述】:
提供代码 M.R.E。
症状是'简单':
- 尝试
hello\nhello\nhelloEOF并插入'_'@ln=2和col=1(或者更确切地说是任何line>1 && col==1)程序好奇地做对了,但吃掉了@ 987654327@ ,导致第 2 行与第 1 行 融合 -hello_hello\nhelloEOF,而不是hello\n_hello\nhelloEOF。 - 尝试在文件
hello\nhello\nhelloEOF的最后一行中使用一个字符并插入'_'@ln=3和col=5(或者更确切地说是在由EOF 终止的行中的任何字符col>1)导致它跳过了该行的最后一个 actual 字符:hello\nhello\nhell_EOF而不是hello\nhello\nhell_oEOF。 - 尝试使用最后一行中的第一个字符(
col==1在由 EOF 终止的行中)会导致抛出错误消息 (\n Invalid Index.)。
就我的直觉而言,我认为在处理线路终止 ('\n',EOF) 及其计数方式以及一般的循环计数器时存在缺陷,但我不明白.
想法/算法:
- 从用户处获取源文件
- 从用户处获取索引(行、列)
- 从源文件复制到 tmp 文件直到(用户的索引 -1 col)。
- 现在,允许用户将字符串写入 tmp 文件的缓冲区。
- 一旦用户终止输入,从用户索引复制到 tmp 直到
EOF。 - 重命名/删除+重命名 tmp 作为用户源文件的名称。
下面的代码做了所有真正的谈话:
#include <stdio.h>
#include <string.h>
/* Likely error region in chknmove(), chkncpy() and/or main() ;
All other functions used are also provided */
long long lncnt(FILE *lcount){
/* counts the number of lines in a file with fgets() */
rewind(lcount); /* ensures lines counted from beginning */
long long lines=0; char line[501];
while((fgets(line,501,lcount))!=NULL){
lines++;
}
rewind(lcount); /* leaves fptr @ 0,0 rather than EOF */
return lines;
}
int chknmove(FILE *tomove, long long line, long long col){
/* Function to check & move FILE* to certain line/col */
rewind(tomove); /* make sure fptr is at beginning of file */
int f=0; /* set check-variable to 0 for successful */
if(line<1 || col<1)
f = -1; /* Ln,col cannot be -ve or even 0 -> 1st col is @ 1ln,1col in any non-empty file */
else{
long long i,q; i=1;q=0; /* i = lines seen, q = cols seen */
/* i init to 1 for ease of comprehension v/s testing 'line-1' */
while(i<line || q<col){ /* loop must iterate until i==line && q==col */
int ch = fgetc(tomove); /* int to store EOF */
if(ch==EOF){
f=-1; break; /* if file ends before reaching index, failed. */
}
else if(ch=='\n') {
if(i==line){
f=-1; break;/* if line ends before reaching col in ln, failed. */
}
i++; q=0; /* else , increase i by 1 and set q (col) to 0 */
}
else
q++; /* any other character is 'normal' , just increment q (col) by 1 */
}
}
if(f==0){
fseek(tomove,-1,SEEK_CUR);
/* since index must be checked, loop reaches it -> fseek(-1) causes *next* r/w to fptr to be on the index . */
return 0;
}
else{
/* f != 0 : moving has failed. */
printf("\n Invalid Index.\n");
return -1;
}
}
int chkncpy(FILE *source, FILE *dest,long long beginln, long long begincol, long long endln, long long endcol){
rewind(source); int f=0;
if(beginln<1 || begincol<1 || endln<beginln || endcol<1 || (beginln==endln && endcol<begincol))
f=-1; /* line/col must be >= 1 in non-empty file, copying done top to bottom (begin-index <= end-index ) */
else{
if(chknmove(source,beginln,begincol)==0){
/* loop begins if begin-index is valid */
long long i,q; i=beginln;q=begincol; /* i = lines, q = cols */
while(i<endln || q<endcol){
/* while end-index is not reached : !(i==endln && q==endcol) */
int ch = fgetc(source);
if(ch==EOF) {f=-1; break;} /* File ends b/w begin-index & end-index - failed. */
else if(ch=='\n') {
if(i==endln) {f=-1; break;} /* endln ends before reaching endcol - failed */
i++; q=0;
fputc(ch,dest); /* valid '\n' put in dest file */
}
else{
q++; fputc(ch,dest); /* valid char put in dest file */
}
}
}
else f=-1; /* if begin-index is invalid, failed. */
}
if(f==-1){
/* if f != 0 : chkncpy() failed */
printf("\n Invalid Index.\n");
return -1;
}
else /* if f remains == 0 */ return 0;
}
long long lastlncol(FILE *fyl){
rewind(fyl); /* makes sure fptr @ beginning */
chknmove(fyl,lncnt(fyl),1); /* move to last line */
long long cnt=0; /* cnt stores no. of chars in last line */
while(1){
int g = fgetc(fyl);
if (g==EOF)
break; /* EOF not counted */
else if(g=='\n'){
cnt++;break; /* \n is counted as a char, but also as EOL */
}
else
cnt++; /* all other chars counted */
}
rewind(fyl); /* leaves file at its beginning */
return cnt;
}
long long lcc(FILE *fyl,long long line){
rewind(fyl); int f = chknmove(fyl,line,1); /* moves fptr to line */
long long cnt=0;
if(f==0){
while(1){
int g = fgetc(fyl);
if (g==EOF)
break;
else if(g=='\n'){
cnt++;break;
}
else
cnt++;
}
rewind(fyl);
return cnt;
}
else
return -1;
}
void writer(FILE *write, int ctrl){
printf("\n Terminate Input with \"/end/\".\n\n Type below :\n\n");
char in[501]; /* str that stores input line-by-line */
char *p; int o;
while(1){
fgets(in,501,stdin); /* takes line from user */
if((p=strstr(in,"/end/"))!=0){
/* if line has "/end/", all chars till /end/ are written to file and input loop breaks */
o = p-in;
fprintf(write,"%.*s",o,in);
break;
}
else{
/* writes line to file */
fputs(in,write);
}
}
if(ctrl==0){
/* in some cases, file must not be closed yet , hence ctrl is taken */
int s = fclose(write);
if(s==EOF) printf("\n Error ");
else printf("\n Success.\n");
}
}
void eat() /* clears stdin */
{
int eat;while ((eat = getchar()) != '\n' && eat != EOF);
}
int main(){
/* main to add/insert to file @ given index */
char fadd[501];/* filename str */
printf("\n Filename : "); scanf("%500[^\n]",fadd);
FILE * add = fopen(fadd,"r");
if(add==NULL)
perror("\n Error "); /* if file does not pre-exist */
else{
long long line, col; char sep; printf("\n Index : "); scanf("%lld%c%lld",&line,&sep,&col); /* takes index in ln-char-col form */
eat(); /* clears stdin */
FILE * tmp=fopen("Temp.Ctt","w"); /* opens a tmp file to write */
if(tmp==NULL)
perror("\n Error "); /* failed - tmp file could not be created to write */
else{
int f; /* success var */
if(line==1 && col>1){
/* if user wants to insert @ a col>1 in line 1 */
f = chkncpy(add,tmp,1,1,line,col); /* all below calls intend to write till 1 char before the char @ given index */
}
else if(line>1 && col>1){
/* if user wants to insert @ a col>1 in any line>1*/
f = chkncpy(add,tmp,1,1,line,col-1);
}
else if(line>1 && col==1){ //ERRORS - ignores the '\n' of line-1
/* if user wants to insert @ a 1st col in line>1 */
f = chkncpy(add,tmp,1,1,line-1,lcc(add,line-1));
}
else if(line==1 && col==1){
/* if user wants to insert @ 1,1 (no moving/copying needed) */
f=0;
}
else{
printf("\n Invalid Index.\n");f=-1;
}
if(f==0){
writer(tmp,1);
/* calls function to allow user to write to fptr , with ctrl != 0, so writer() *won't* fclose(tmp) */
chkncpy(add,tmp,line,col,lncnt(add),lastlncol(add));
/* copies all characters from index till EOF */
int ok = fclose(tmp); fclose(add);
if(ok==EOF){
/* if closing tmp was unsuccessful, the file on disk may be corrupted/incomplete, so must be removed */
remove("Temp.Ctt");perror("\n Error ");
}
else{
if(rename("Temp.Ctt",fadd)==0)
printf("\n Success.\n");
else{
/* on Windows & some other non-POSIX systems, file cannot be renamed to pre-existing filename , hence delete original */
remove(fadd);
if(rename("Temp.Ctt",fadd)==0)
printf("\n Success.\n");
else{
/* if rename still unsuccessful, throw an error, remove tmp file and give up */
remove("Temp.Ctt");
perror("\n Error ");
}
}
}
}
}
}
}
如果有任何遗漏的细节或无意的错误,请发表评论,我会更正。
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
-
@SamuelLiew 如果评论线程看起来有点大,除了版主干预之外,我们有没有办法将它移动到我们自己聊天?
标签: c file file-io file-pointer