在这段代码中,我在open_file函数中打开了我的文件。然后,process_file函数需要从我的in文件中复制文本并将其复制到out文件中。现在它生成一个新文件,但它是空白的。它没有给我任何错误消息。我不知道出了什么问题。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX_LEN 100
FILE* open_file(char prompt[], char mode[]);
FILE* process_file(FILE* in, FILE* out);
int main(int argc, const char * argv[]) {
FILE* in = NULL;
FILE* out = NULL;
printf("MAD-LIBS Text Processor\n");
printf("The Program will open a mad-libs file, ask you to fill various words, and produce a funny story.\n");
open_file("Enter mad-lib file name:\n", "r");
open_file("Enter file name for resulting story:\n", "w");
process_file(in, out);
fclose(in);
fclose(out);
return 0;
}
/* open_file = prompts user for file name & and attempts to open it, if it fails it prompts the user again. */
FILE* open_file(char prompt [], char mode[]) {
char filename[255];
FILE* in;
do {
printf("%s", prompt);
scanf("%s", filename);
in = fopen(filename, mode);
if (in == NULL) {
printf("Unable to open file: %s. Try Again!\n", filename);
}
} while(in == NULL);
return in;
}
/* process_file = processes entire input file and writes it to output file */
FILE* process_file(FILE* in, FILE* out) {
char content[MAX_LEN];
char NewContent[MAX_LEN];
//gets whats in file in
while(fgets(content, content[MAX_LEN], in) != NULL) {
fputs (content, stdout);
strcat(NewContent, content);
}
// copies it
while (fgets(content, content[MAX_LEN], in) != NULL) {
fprintf(out, "%s", content);
}
printf("Successfully copied file\n");
return in;
}
答案 0 :(得分:1)
您永远不会将FILE*
从open_file
函数分配给您的变量,因此永远不会被处理。
in = open_file("Enter mad-lib file name:\n", "r");
out = open_file("Enter file name for resulting story:\n", "w");
答案 1 :(得分:1)
您没有存储FILE
正在返回的open_file
指针,因此in
并且out
仍然没有初始化。
你必须这样做:
in = open_file("Enter mad-lib file name:\n", "r");
out = open_file("Enter file name for resulting story:\n", "w");
process_file(in, out);
您的process_file
也是错误的。当您执行
NewContent
未初始化
strcat(NewContent, content);
这会产生未定义的行为。像这样声明NewContent
:
char NewContent[MAX_LEN] = { 0 };
以便正确\0
- 终止。
另外,根据您要复制的文件的大小,MAX_LEN
可能不是
足够长的时间来容纳整个文件。在这种情况下,您将溢出缓冲区。
最好不要首先使用NewContent
并写入out
在相同的阅读循环中:
FILE* process_file(FILE* in, FILE* out) {
char content[MAX_LEN];
//gets whats in file in
while(fgets(content, MAX_LEN, in) != NULL) { //<- your fgets was wrong
fputs (content, stdout);
fprintf(out, "%s", content); // or fputs(content, out);
}
printf("Successfully copied file\n");
return in;
}
你错误地调用fgets
(查看我更正的代码)
还要记住,你确实有2个循环while(fgets(...) != NULL
。
好吧,第一个循环结束,那是因为fgets
最有可能返回NULL
因为读取了整个文件或发生了I / O错误。在任一情况下
fgets
的后续调用也将返回NULL
,因此您的第二个循环
根本不会被执行。