使用C编辑文件
input.txt:
File entry structures:
[0] "" 0 -1
[1] "" 0 -1
[2] "" 0 -1
[3] "" 0 -1
[4] "" 0 -1
我想创建一个新文件(output.txt)。 C程序取代了“ TestFile”的第一次出现,因此看起来像:
output.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
的第二个参数上。 。我的目标是以与输入文件中相同的方式编写。
Input.txt:
File entry structures:
[0] "" 0 -1
[1] "" 0 -1
[2] "" 0 -1
[3] "" 0 -1
[4] "" 0 -1
I want to create a new file (output.txt). The C program replaces the first occurrence of "" with "Testfile", so it looks like:
Output.txt:
File entry structures:
[0] "Testfile" 0 -1
[1] "" 0 -1
[2] "" 0 -1
[3] "" 0 -1
[4] "" 0 -1
My work so far:
#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, ... );
}
I'm lost on what to provide to the second parameter of fprintf
. My goal is to write it in the same way as it was in the input file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你努力工作。我拖延了太多。这可以使用非常简单的状态机来完成:
You're working too hard. And I am procrastinating too much. This can be done with a very simple state machine:
可能有很多解决此问题的方法,因此,这是一种建议进行此操作的方法。在您的程序中,我添加了一些字符串检查和操纵,以产生与数据记录相关的字面“ testfile”所需的结果。以下是您程序的修订版。
我为您的审核完成了“ FPRINTF”功能的格式。另外,“ strcmp”和“ strcpy”功能来自“&lt; string.h&gt;”用于提供“记录[0]”的搜索/替换。
当我使用您的示例数据运行此程序时,这是输出文件中的数据显示方式。
正如我指出的那样,可能还有其他方法可以找到您想要的结果,但这应该为您提供一个起点。
希望有帮助。
问候。
There probably are a lot of ways to solve this, so here is a suggested way to do this for your review. In your program, I added in some string checking and manipulation to produce the desired outcome of having the literal "Testfile" associated with the first record of your data. Following is a revised version of your program.
I completed the formatting for the "fprintf" function for your review. Also, the "strcmp" and "strcpy" functions from "<string.h>" were used to provide the search/replace for "Record [0]".
When I ran this program using your sample data, here is how the data in the output file appeared.
As I noted, there are probably other ways to get to the results you want, but this should provide a starting point for you.
Hope that helps.
Regards.