文件读写同一文件?
我已经成功打开一个文件并在写入另一个文件时读取文件 var=fopen(file,"r")
/ "w"
但即使使用 r+ 或 w+ moded 我无法打开文件并更改其内容。
想象一下:
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);
}
完美无缺!如何打开文件,逐个字符读取并决定是否要更改字符?
I've managed to open a file and read while writing to another file with var=fopen(file,"r")
/ "w"
but even with r+ or w+ moded I can't open a file and alter its contents.
Imagine this:
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);
}
Code works, no errors, no warning, only problem is: it erases the contents on the file if I use it like this BUT this works:
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);
}
Flawlessly! How can I open a file, read char by char and decide if I want to change the char or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以附加模式打开文件
Open file in append mode
您需要在输出和输入之间插入文件定位功能,除非在输入上找到 EOF。
这对我有用:
You need to intervene a file positioning function between output and input unless EOF was found on input.
This works for me:
使用“a+”选项打开文件,以便附加到文件:
w+ 将删除文件(如果存在)或创建新文件(如果指定的文件不存在)。 a+ 将打开现有文件,您将能够对其进行编辑。
您可以在此处阅读有关文件操作的更多信息:http://www.functionx.com/cppbcb/cfileprocessing。嗯
Open the file with 'a+' option, in order to append to the file:
w+ will erase your file if exists or create new if the specified doesn't exist. a+ will open the existing file and you will be able to edit it.
You can read more about file operations here: http://www.functionx.com/cppbcb/cfileprocessing.htm