C 中的文件 I/O - 如何从文件读取然后写入文件?
File I/O in C - How to read from a file and then write to it?
我是 C 文件 i/o 的新手,在我的代码中,我想从文本文件中读取信息,然后写入其中。
我尝试使用 fopen("file.csv", "r+t") 打开一个 csv 文件,以便能够读取然后写入同一个文件。所以我用了fgetc,然后又用了fputc,但是不知为何,fputc函数并没有起作用。当我尝试切换顺序时,字符毫无问题地打印到文件中,但看起来 fgetc 在下一个位置放置了一个未知字符。
我做错了什么,或者实际上不可能在同一个流中读取和写入文件?感谢您的帮助!
打开文件进行读写时,在操作之间切换时使用 fseek()。 fseek( fp, 0, SEEK_CUR);
不改变文件指针在文件中的位置。
#include<stdio.h>
#include<stdlib.h>
int main ( ) {
int read = 0;
int write = 48;
int each = 0;
FILE *fp;
fp = fopen("z.txt", "w");//create a file
if (fp == NULL)
{
printf("Error while opening the file.\n");
return 0;
}
fprintf ( fp, "abcdefghijklmnopqrstuvwxyz");
fclose ( fp);
fp = fopen("z.txt", "r+");//open the file for read and write
if (fp == NULL)
{
printf("Error while opening the file.\n");
return 0;
}
for ( each = 0; each < 5; each++) {
fputc ( write, fp);
write++;
}
fseek ( fp, 0, SEEK_CUR);//finished with writes. switching to read
for ( each = 0; each < 5; each++) {
read = fgetc ( fp);
printf ( "%c ", read);
}
printf ( "\n");
fseek ( fp, 0, SEEK_CUR);//finished with reads. switching to write
for ( each = 0; each < 5; each++) {
fputc ( write, fp);
write++;
}
fseek ( fp, 0, SEEK_CUR);//finished with writes. switching to read
for ( each = 0; each < 5; each++) {
read = fgetc ( fp);
printf ( "%c ", read);
}
printf ( "\n");
fclose ( fp);
return 0;
}
产出
该文件最初包含
abcdefghijklmnopqrstuvwxyz
读写后包含
01234fghij56789pqrstuvwxyz
我是 C 文件 i/o 的新手,在我的代码中,我想从文本文件中读取信息,然后写入其中。 我尝试使用 fopen("file.csv", "r+t") 打开一个 csv 文件,以便能够读取然后写入同一个文件。所以我用了fgetc,然后又用了fputc,但是不知为何,fputc函数并没有起作用。当我尝试切换顺序时,字符毫无问题地打印到文件中,但看起来 fgetc 在下一个位置放置了一个未知字符。 我做错了什么,或者实际上不可能在同一个流中读取和写入文件?感谢您的帮助!
打开文件进行读写时,在操作之间切换时使用 fseek()。 fseek( fp, 0, SEEK_CUR);
不改变文件指针在文件中的位置。
#include<stdio.h>
#include<stdlib.h>
int main ( ) {
int read = 0;
int write = 48;
int each = 0;
FILE *fp;
fp = fopen("z.txt", "w");//create a file
if (fp == NULL)
{
printf("Error while opening the file.\n");
return 0;
}
fprintf ( fp, "abcdefghijklmnopqrstuvwxyz");
fclose ( fp);
fp = fopen("z.txt", "r+");//open the file for read and write
if (fp == NULL)
{
printf("Error while opening the file.\n");
return 0;
}
for ( each = 0; each < 5; each++) {
fputc ( write, fp);
write++;
}
fseek ( fp, 0, SEEK_CUR);//finished with writes. switching to read
for ( each = 0; each < 5; each++) {
read = fgetc ( fp);
printf ( "%c ", read);
}
printf ( "\n");
fseek ( fp, 0, SEEK_CUR);//finished with reads. switching to write
for ( each = 0; each < 5; each++) {
fputc ( write, fp);
write++;
}
fseek ( fp, 0, SEEK_CUR);//finished with writes. switching to read
for ( each = 0; each < 5; each++) {
read = fgetc ( fp);
printf ( "%c ", read);
}
printf ( "\n");
fclose ( fp);
return 0;
}
产出
该文件最初包含
abcdefghijklmnopqrstuvwxyz
读写后包含
01234fghij56789pqrstuvwxyz