gpt4 book ai didi

c - 使用 C 编辑文件

转载 作者:行者123 更新时间:2023-12-05 08:03:29 24 4
gpt4 key购买 nike

输入.txt:

File entry structures:
[0] "" 0 -1
[1] "" 0 -1
[2] "" 0 -1
[3] "" 0 -1
[4] "" 0 -1

我想创建一个新文件 (output.txt)。 C 程序将第一次出现的“”替换为“Testfile”,因此它看起来像:

输出.txt:

File entry structures:
[0] "Testfile" 0 -1
[1] "" 0 -1
[2] "" 0 -1
[3] "" 0 -1
[4] "" 0 -1

我目前的工作:

#include <stdio.h>

int main() {
FILE *input_file, *output_file;
int size, fblock;
char index[81];
char name[81];


input_file = fopen("input.txt", "r");

output_file = fopen("output.txt", "w");

// ignore "File entry structures:" line when reading/writing

while (fscanf(input_file, "%80s %80s %d %d", index, name, &size, &fblock) == 4) {
fprintf(output_file, ... );
}



我不知道要为 fprintf 的第二个参数提供什么。我的目标是以与输入文件中相同的方式编写它。

最佳答案

你太辛苦了。我太拖延了。这可以通过一个非常简单的状态机来完成:

#include <stdlib.h>
#include <stdio.h>

FILE * xfopen(const char *path, const char *mode);

int
main(int argc, char **argv)
{
int c;
int seen = 0;
FILE *in = argc > 1 ? xfopen(argv[1], "r") : stdin;
FILE *out = argc > 2 ? xfopen(argv[2], "r") : stdout;

while( (c = fgetc(in)) != EOF ){
if( seen == 0 && c == '"' ){
int d = fgetc(in);
if( d == '"' ){
fputs("\"Testfile", out);
seen = 1;
} else {
ungetc(d, in);
}
}
fputc(c, out);
}
return 0;
}

FILE *
xfopen(const char *path, const char *mode)
{
FILE *fp = path[0] != '-' || path[1] != '\0' ? fopen(path, mode) :
*mode == 'r' ? stdin : stdout;
if( fp == NULL ){
perror(path);
exit(EXIT_FAILURE);
}
return fp;
}

关于c - 使用 C 编辑文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72627557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com