我已经设法打开一个文件并在写入另一个文件时读取var=fopen(file,"r")
/"w"
,但即使使用r+或w+模式,我也无法打开文件并更改其内容。
想象一下:
int formatacao (char original[]){/*se a cadeia nao tiver escrita em maiusculas, esta funçao vai alteralas para tal*/
int val1;
FILE * original_open;
original_open = fopen (original,"r+");
if (original_open==0){
printf ("ficheiro %c 1.",original);
}
while ((val1=fgetc(original_open))!=EOF){
if (val1>='a'&&val1<='z'&&val1){
fputc(val1-32,original_open);
}
else
fputc(val1,original_open);
}
fclose (original_open);
return (0);
}
代码工作,没有错误,没有警告,唯一的问题是:如果我像这样使用它,它会擦除文件上的内容,但是这工作:
int main (){
int val1,val2,nr=0;
FILE* fp1;
FILE* fp2;
fp1=fopen ("DNAexample.txt","r");
fp2=fopen ("DNAexample1.txt","w");
if (fp1==0){
printf ("EPIC FAIL no 1.n");
}
while ((val1=fgetc(fp1))!=EOF){
if (val1>='a'&&val1<='z'&&val1){
fputc(val1-32,fp2);
}
else
fputc(val1,fp2);
}
fclose (fp1);
fclose (fp2);
return (0);
}
完美!我怎么能打开一个文件,读字符字符和决定我是否要改变字符或不?
您需要在输出和输入之间干预文件定位函数,除非在输入上发现EOF。
这个对我有效:
#include <stdio.h>
int formatacao (char *original) {
int val1;
FILE *original_open;
int write_at, read_at;
original_open = fopen(original, "r+");
if (original_open == 0) {
printf("ficheiro %sn", original);
}
write_at = read_at = 0;
while ((val1 = fgetc(original_open)) != EOF) {
read_at = ftell(original_open);
fseek(original_open, write_at, SEEK_SET);
if (('a' <= val1) && (val1 <= 'z')) {
fputc(val1 - 32, original_open);
} else {
fputc(val1, original_open);
}
write_at = ftell(original_open);
fseek(original_open, read_at, SEEK_SET);
}
fclose(original_open);
return (0);
}
int main(void) {
formatacao("5787867.txt");
return 0;
}
使用'a+'选项打开文件,以便在文件中追加内容:
fopen ("DNAexample.txt","a+");
w+将删除文件,如果指定的文件不存在,则创建新文件。A +将打开现有文件,您将能够编辑它。
您可以在这里阅读更多关于文件操作的信息:http://www.functionx.com/cppbcb/cfileprocessing.htm
以追加方式打开文件
original_open = fopen (original,"a+");