簡體   English   中英

在C程序中將兩個文件合並為一列

[英]Two files into one column in C Program

我試圖弄清楚為什么我在終端上執行gcc命令時仍然收到錯誤消息,並且代碼和編譯器也都包含了該消息。 誰能知道為什么或可以幫助我嗎? 這個學期我真的是C程序的新手。 這是一個主要功能,它使用命令行參數來打開兩個文件,並將兩個文件一次一行地組合成一個輸出。 第一個文件是文本行,但是請刪除每行末尾的所有空格(換行符,制表符和空格),第二個文件是數字列表。 因此,應該有兩列用字符分隔。 以我為例,您可以直觀地進行進一步說明:

  Example for to output:
  ./p2 test/p2-testa test/p2-testb
  Test A  11
  Test B  51
  Test C  91
  Test D  26
  Test E  17
  Test F  76


/* 3 point */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

const int MAXLEN = 4096;
const int MAXLINES = 10;

int main(int argc, char *argv[]) {

  char buffer[MAXLEN];
  char buffer2[MAXLEN];
  FILE *fp = fopen(argv[1], "r");
  FILE *fp2 = fopen(argv[2], "r");

  if (!(fp && fp2)) {
    perror ("Not Found");
    exit (EXIT_FAILURE);
  }

  int n = 0;
  while((n < MAXLINES) && (fgets (buffer, sizeof (buffer), fp)) && (fgets(buffer2, sizeof (buffer2), fp2))) {
    printf("%s\t%s", buffer, buffer2);
    n++;
  }

  fclose((fp) && (fp2));    
  return (0);

}

錯誤編譯消息(順便說一句:對於授課,我使用了labcheck ):

p2:
p2.c: In function ‘main’:
p2.c:52:19: warning: passing argument 1 of ‘fclose’ makes pointer from integer without a cast [-Wint-conversion]
       fclose((fp) && (fp2));
              ~~~~~^~~~~~~~
In file included from p2.c:2:
/usr/include/stdio.h:199:26: note: expected ‘FILE *’ {aka ‘struct _IO_FILE *’} but argument is of type ‘int’
 extern int fclose (FILE *__stream);
                    ~~~~~~^~~~~~~~
-3.0 output of program (p2) is not correct for input '/u1/h7/CS151/.check/text/list.1 /u1/h7/CS151/.check/nums/tiny.1':
------ Yours: ------
---- Reference: ----
Line A  6
Line B  41
Line C  52
Line D  3
Line E  36
Line F  61
--------------------

我不太了解C程序中的警告和預期消息。

傳遞給fclose表達式(fp) && (fp2)由運算符&&組合兩個指針,該指針期望整數操作數並將其解釋為==0!=0 結果是一個整數值,該值還是==0!=0 ,但它與fclose期望的指針無關。

所以fclose((fp) && (fp2))應該是

fclose(fp);
fclose(fp2);

您的程序應該看起來像這樣

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

const int MAXLEN = 4096;
const int MAXLINES = 10;

int main(int argc, char *argv[]) {

  char buffer[MAXLEN];
  char buffer2[MAXLEN];
  FILE *fp = fopen(argv[1], "r");
  FILE *fp2 = fopen(argv[2], "r");

  if (!(fp && fp2)) {
    perror ("Not Found");
    exit (EXIT_FAILURE);
    }

     int n = 0;
       while((n < MAXLINES) && (fgets (buffer, sizeof (buffer), fp)) && (fgets(buffer2, sizeof (buffer2), fp2))) {
           printf("%s\t%s", buffer, buffer2);
               n++;

}
      fclose(fp);
      fclose(fp2);

      return (0);

      }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM