我正在编写一个C程序,它将读取和合并3个文件(程序尚未完成),但是,当我进行测试时,我意识到该程序可以编译,但是控制台上的屏幕仍然空白!
感谢您的帮助,尤其是为什么空白?
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("test");
//open three files for merging
FILE *fp1 = fopen("american0.txt","r");
FILE *fp2 = fopen("american1.txt","r");
FILE *fp3 = fopen("american2.txt","r");
printf("test");
//open file to store the result
FILE *fpm = fopen("words.txt", "w");
//creating an array to save the files data
char c;
char mergedFile[50];
//checking to make sure files are being read
if(fp1 == NULL && fp2 == NULL && fp3 == NULL && fpm == NULL)
{
printf("Could not open one or all of the files.\n");
printf("Exiting program!");
exit(0);
}
printf("test");
//initializing counter values
//inserting data from file into an array
while ((c = fgetc(fp1)) != EOF)
{
fputc(c, mergedFile);
}
while ((c = fgetc(fp2)) != EOF)
{
fputc(c, mergedFile);
}
while ((c = fgetc(fp3)) != EOF)
{
fputc(c, mergedFile);
}
printf("%s",mergedFile[0]);
printf("test");
return 0;
}
答案 0 :(得分:2)
错误-> fputc
需要使用文件指针作为第二个参数,而不是数组:int fputc ( int character, FILE * stream );
要注意的要点:
char
数组中的要求。这是一个最低限度的更正版本:
#include <stdio.h>
#include <stdlib.h>
#define MAX 1000 //ADDED NEW
int main()
{
//open three files for merging
FILE *fp1 = fopen("american0.txt","r");
FILE *fp2 = fopen("american1.txt","r");
FILE *fp3 = fopen("american2.txt","r");
//open file to store the result
FILE *fpm = fopen("words.txt", "w");
//creating an array to save the files data
int c;
int i=0;
char mergedFile[MAX]={0}; //MODIFIED & INITIALIZED
//checking to make sure files are being read
if(fp1 == NULL && fp2 == NULL && fp3 == NULL && fpm == NULL)
{
printf("Could not open one or all of the files.\n");
printf("Exiting program!");
exit(0);
}
//initializing counter values
//inserting data from file into an array
while (((c = fgetc(fp1)) != EOF)&&(i<MAX)) //MODIFIED
{
mergedFile[i++]=c; //MODIFIED
}
while (((c = fgetc(fp2)) != EOF)&&(i<MAX)) //MODIFIED
{
mergedFile[i++]=c; //MODIFIED
}
while (((c = fgetc(fp3)) != EOF)&&(i<MAX)) //MODIFIED
{
mergedFile[i++]=c; //MODIFIED
}
printf("%s",mergedFile); //MODIFIED
return 0;
}