C程序符合要求,但控制台上的屏幕保持黑色

时间:2018-09-15 16:01:33

标签: c linux debugging console

我正在编写一个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;
}

1 个答案:

答案 0 :(得分:2)

错误-> fputc需要使用文件指针作为第二个参数,而不是数组:int fputc ( int character, FILE * stream );

要注意的要点:

  1. 数组的大小应足够大以容纳这些文件中的所有数据。
  2. 注意格式说明符及其在char数组中的要求。
  3. 如果数组大小小于所有文件的总大小怎么办? -错误处理
  4. 如果要读取/写入的文件在其他目录中怎么办?

这是一个最低限度的更正版本:

     #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;

     }