2014-12-07 63 views
-1

我需要一些幫助與任務。這是我到目前爲止:IO結果。調整代碼

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

#define MAXN 100 

int main(){ 

    int ch = 0; 
    FILE *fi = NULL; 
    FILE *fo = NULL; 
    int numo = 0; 
    int numi = 0; 
    int nump = 0; 

    fo = fopen("OutputFile.txt", "w+"); 
    if (!fo) { 
     perror ("Error while opening the file.\n"); 
     exit (EXIT_FAILURE); 
    } 

    fi = fopen("InputFile.txt","r"); 

    if(!fi){ 
     perror("Error while opening the file.\n"); 
     exit(EXIT_FAILURE); 
    } 

    printf("\n The contents of %s file are :\n", "InputFile.txt"); 
    while((ch = fgetc(fi)) != EOF) 
     printf("%c",ch); 






    numi = ch; 

    numo = numi + 8; 








    fprintf (fo, " %d\n", numo); 





    if (fo) fclose (fo); 

    return 0; 
} 

編輯3.廢棄陣列的想法,因爲它導致我更麻煩,然後成功。我將這個列表簡化爲inputfile.txt中的一行。數學很簡單,所以我可以看到我在做什麼,哪裏出錯了。我已經有了大部分的工作,只是有點小故障。

首先,程序將讀取文件並將其顯示在程序中。問題出現在該點之後,結果保存到OutputFile.txt中。取決於我使用的%(%s,%i,%d,%c)OutputFile.txt中的結果是-1,一個字符或更長的數字列表。

如何從InputFile.txt獲取號碼並將號碼保存到numi中?

這是什麼樣子

The contents of InputFile.txt are: 10010110 
numo=ch+8 
Result (Numo) save to OutputFile.txt 

當我打開OutputFile.txt行讀7.因此,由於某種原因,CH = -1(我想讓它等於10010110),我不知道-1來自哪裏。

+0

你不知道過了多久是你的文件,所以您需要動態的第一件事分配內存('malloc()','realloc()','free()')http://www.cplusplus.com/reference/cstdlib/malloc/。你將動態分配二維數組(二進制數的指針數組)的內存http://stackoverflow.com/questions/19920452/dynamically-allocated-2-dimensional-array。在進行計算後,使用'fprinf()'將結果保存到文件中http://www.tutorialspoint.com/c_standard_library/c_function_fprintf.htm。 – 2014-12-07 20:52:08

+0

也許你應該節省一些時間和記憶,並在讀完整行後直接進行計算。希望這會幫助你。 – 2014-12-07 21:00:17

+0

我放棄了數組的想法,並且我在OutputFile.txt中打印了SOMETHING。更新了原帖中的代碼。 – Zee 2014-12-07 21:46:44

回答

0

有很多方法可以把拼圖拼湊在一起。找到工作的工具是1/2的戰鬥。在這種情況下,strtol將基數2轉換爲小數。關鍵是要認識到,沒有理由去做character input,你可以使用line-oriented input來簡化你的代碼,這將提供你的數據格式準備轉換。

下面是拼圖的部分。它們會有些失序,因此您可以重新排列它們以生成一個最終輸出文件,其中包含字符串和十進制值。在讀取文本文件之前,您可能需要打開輸出文件,以便在讀取循環期間兩個文件流都可用。

如果您有任何問題,請來看看並告訴我。 注:這只是很多很多方法可以解決這個問題之一:

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

#define MAXN 100 

int main() { 

    char file_input[25] = { 0 }; /* always initialize all variables */ 
    char file_output[25] = { 0 }; 
    FILE *fi = NULL; 
    FILE *fo = NULL; 
    int integers[MAXN] = { 0 }; 
    int i = 0; 
    int num = 0; 

    printf ("\n Please enter the input filename: "); 
    while (scanf ("%[^\n]%*c", file_input) != 1) 
     fprintf (stderr, "error: read failed for 'file_input', try again\n filename: "); 

    fi = fopen (file_input, "r"); /* open input file and validate  */ 
    if (!fi) { 
     perror ("Error while opening the file.\n"); 
     exit (EXIT_FAILURE); 
    } 

    printf ("\n The contents of file '%s' are :\n\n", file_input); 

    char *line = NULL;    /* NULL forces getline to allocate */ 
    size_t n = 0;     /* max chars to read (0 - no limit */ 
    ssize_t nchr = 0;    /* number of chars actually read */ 

    while ((nchr = getline (&line, &n, fi)) != -1) { 

     if (line[nchr - 1] == '\n') 
      line[--nchr] = 0;  /* strip newline from end of line */ 

     integers[i] = strtol (line, NULL, 2); /* convert to decimal  */ 

     printf (" %s -> %d\n", line, integers[i]); 

     if (i == MAXN - 1) {  /* check MAXN limit not exceeded */ 
      fprintf (stderr, "error: input lines exceed %d\n", MAXN); 
      exit (EXIT_FAILURE); 
     } 

     i++; 
    } 

    if (line) free(line);   /* free memory allocated by getline */ 
    if (fi) fclose (fi);   /* close file stream when done  */ 

    num = i;      /* save number of elements in array */ 

    printf ("\n Conversion complete, output filename: "); 
    while (scanf ("%[^\n]%*c", file_output) != 1) 
     fprintf (stderr, "error: read failed for 'file_output', try again\n filename: "); 

    fo = fopen (file_output, "w+"); /* open output file & validate  */ 
    if (!fo) { 
     perror ("Error while opening the file.\n"); 
     exit (EXIT_FAILURE); 
    } 

    for (i = 0; i < num; i++)  /* write integers to output file */ 
     fprintf (fo, " %d\n", integers[i]); 

    if (fo) fclose (fo); 

    return 0; 
} 

使用/輸出:

$ ./bin/arrayhelp 

Please enter the input filename: dat/binin.txt 

The contents of file 'dat/binin.txt' are : 

    01000101 -> 69 
    11010110 -> 214 
    11101110 -> 238 

Conversion complete, output filename: dat/binout.txt 

$ cat dat/binout.txt 
69 
214 
238 

讀取字符一個字符

雖然這不是處理讀取文件的最簡單方法,但是它沒有錯。但是,你有邏輯問題。具體而言,您讀取(並分配爲整數)numi = ch;,然後分配numo = numi + 8;以寫入您的輸出文件。這導致增加8到的'0'()或'1'()的ASCII值。如果您將添加到那,那麼您可以進行數學計算。當您從文件中讀取文本時,您正在閱讀的是ASCII值,不是的數值10

爲了完成你似乎正在嘗試的東西,你必須把所有的字符都保存在一個緩衝區(一個string,一個character array,我不介意你稱之爲什麼)。這是唯一的辦法,(必須將字符逐字符轉換爲數字10,然後再執行binary addition),則必須將'0' s和'1' s的字符串轉換爲十進制值。

以下是使用從fi讀取的character-by-character的示例。閱讀它並理解爲什麼需要這樣做。如果您有任何問題,請刪除其他評論。

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

#define MAXN 100 

int main() { 

    int ch = 0; 
    FILE *fi = NULL; 
    FILE *fo = NULL; 
    // int numo = 0; 
    // int numi = 0; 
    // int nump = 0; 
    char buffer[MAXN] = { 0 };    /* buffer to hold each line  */ 
    int idx = 0;       /* index for buffer    */ 

    fo = fopen ("OutputFile.txt", "w+"); /* open output file & validate */ 
    if (!fo) { 
     perror ("Error while opening the file.\n"); 
     exit (EXIT_FAILURE); 
    } 

    fi = fopen ("InputFile.txt", "r");  /* open input file & validate */ 

    if (!fi) { 
     perror ("Error while opening the file.\n"); 
     exit (EXIT_FAILURE); 
    } 

    printf ("\n The contents of %s file are :\n\n", "InputFile.txt"); 

    fprintf (fo, " binary  decimal\n"); /* header for output file */ 

    while (1) /* loop and test for both '\n' and EOF (-1) to parse file */ 
    { 
     // printf ("%c", ch);  /* we will store each ch in line in buffer */ 

     if ((ch = fgetc (fi)) == '\n' || ch == EOF) 
     { 
      if (ch == EOF && idx == 0) /* if EOF (-1) & buffer empty exit loop */ 
       break; 
      buffer[idx] = 0;  /* null-terminate buffer (same as '\0') */ 
      idx = 0;    /* reset index for next line & continue  */ 
            /* write original value & conversion to fo */ 
      fprintf (fo, " %s => %ld\n", buffer, strtol (buffer, NULL, 2)); 
            /* write fi contents to stdout (indented) */ 
      printf (" %s\n", buffer); 
     } 
     else 
     { 
      buffer[idx++] = ch;  /* assign ch to buffer, then increment idx */ 
     } 

     /* This makes no sense. You are reading a character '0' or '1' from fi, 
     the unsigned integer value is either the ASCII value '0', which is 
     decimal 48 (or hex 0x30), or the ASCII value '1', decimal 49/0x31. 
     If you add 8 and write to 'fo' with '%d' you will get a 16-digit 
     string of a combination of '56' & '57', e.g. 56575756.... 

      numi = ch; 
      numo = numi + 8; 
     */ 
    } 

    if (fi)       /* close both input and output file streams */ 
     fclose (fi); 
    if (fo) 
     fclose (fo); 

    return 0; 
} 

輸出到標準輸出:

$ ./bin/arrayhelp2 

The contents of InputFile.txt file are : 

    01000101 
    11010110 
    11101110 

OutputFile.txt:

$ cat OutputFile.txt 
    binary  decimal 
    01000101 => 69 
    11010110 => 214 
    11101110 => 238 
+0

謝謝。我會看看我能否想出來並在稍後發佈結果:D – Zee 2014-12-07 22:19:30

+0

編輯原始帖子,我現在在哪裏。你的帖子對於弄清楚這些代碼有很大的幫助,儘管我對ssize_t有一些問題並報廢了陣列的想法......我現在處於最後一段代碼,我只是不確定爲什麼-1正在當我試圖讓它保存在InputFile.txt中的數字時保存爲CH。 – Zee 2014-12-08 00:52:49

+0

查看我的加法標題**閱讀逐字符**保存爲'ch'的'-1'是'EOF'的值... – 2014-12-08 04:58:34