此循环遵循您在块中处理文件的一般方法:
您的方法已修改:
# include <stdio.h>
# include <stdlib.h>
int main() {
FILE *in;
char myStr[100],newStr[100];
int ch;
int j,i,k,z=0;
in=fopen("duom.txt","r");
if(!(in)) { fprintf(stderr,"Error opening file!\n"); }
else { //the file was opened
int go = 1; //master loop control
while(go) { //master loop
z = 0; //set sub loop
ch = '\0';//control variables
while(z < 100 && EOF != ch){ //process file in 99 character blocks
ch=fgetc(in); //getting one character at a time
if(EOF == ch) { go = 0; } //break master loop
else { myStr[z++] = ch; } //or process char
}
myStr[z] = '\0'; //null terminate the string
for(i=0; myStr[i] != '\0'; i++) {
//i=99='\0' <-- assumed is highest string size
//if i=0; Do you really want that leading space?
if(i== 0 && myStr[i] == ' ' ) { continue; }
//if i=98 it is the last char in the string i=99 should be '\0'
//So do you really want that trailing space?
if(i==98 && myStr[i] == ' ' ) { continue; }
//Same rational as above.
//So do you really want those trailing 2 spaces?
if(i==97 && myStr[i] == ' ' && myStr[i+1] == ' ') { continue; }
//if i=0; myStr[i-1] will likely cause a segmentation fault
if(i > 0 && myStr[i] == ' ' && myStr[i+1] == ' ' && myStr[i-1] != '.') { continue; }
newStr[k] = myStr[i];
k++;
}
for(j=0;j<k;j++){ printf("%c",newStr[j]); } //print the 99 char block
}
printf("\n"); //print a newline for good measure
fclose(in); //close file
}
return 0;
}
请注意,对于大小大于 99 字符的文件,代码将出现异常,因为不会从一个 99 字符块的末尾到另一个块的开头进行间距格式比较。您可以通过不删除前导/尾随空格来实现此目的,将 i=1 和 i=2 处的值与前一个块中 i=97 和 i=98 处的最后两个字符进行比较。
这是一个不同的、更好的循环。它解决了其他方法的块屏障问题,并且使用更少的内存
更好的方法:
# include <stdio.h>
# include <stdlib.h>
int main() {
FILE *in;
in=fopen("duom.txt","r");
if(!(in)) { fprintf(stderr,"Error opening file!\n"); return -1; }
//the file was opened
int x; //stores current char
int y; //stores previous char
for(y='\0'; (x=fgetc(in)) != EOF; y=x) { //read in 'x' until end of file
// The following conditions cover all cases:
// is 'x' not a space? Then print 'x'
// is 'x' a space but 'y' a period? Then print two spaces
// is 'x' a space and 'y' not a period but also not a space? Then print a space
// Otherwise 'x' is part of extra spacing, do nothing
if(x != ' ') { printf("%c",x); }
else if(x == ' ' && y == '.') { printf(" "); }
else if(x == ' ' && y != '.' && y != ' ') { printf(" "); }
else { ; } //do nothing
}
printf("\n"); //print a newline for good measure
fclose(in); //close file
return 0;
}