【问题标题】:IO results. Tweak the code [duplicate]IO 结果。调整代码[重复]
【发布时间】:2015-02-05 11:51:31
【问题描述】:

我需要一些帮助来完成一项任务。这是我目前所拥有的:

#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 的来源。

【问题讨论】:

标签: c arrays io


【解决方案1】:

有很多方法可以将拼图的各个部分拼凑在一起。找到工作的工具是战斗的 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' (48) 或'1' (49) 的ASCII 值。如果您将 8 添加到其中,那么您可以进行数学计算。当您以 text 的形式从文件中读取时,您读取的是 ASCII 值,NOT 是数值 10

为了完成您似乎正在尝试的事情,您必须将一行中的所有字符保存到缓冲区中(stringcharacter array,我不在乎你怎么称呼它)。这是唯一的方法,(除了逐个字符转换为数字10 然后执行binary addition),您必须转换'0's 和@987654339 的字符串@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

输出文件.txt:

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

【讨论】:

  • 非常感谢。我会看看我是否能弄清楚并稍后发布结果:D
  • 用我现在的位置编辑了原始帖子。您的帖子对找出这段代码的一些帮助有很大帮助,尽管我在 ssize_t 方面遇到了一些问题并放弃了数组的想法......我现在处于最后一段代码,我只是不确定为什么 -1 是当我试图让它保存在 InputFile.txt 中的数字时,另存为 CH。
  • 查看我添加的标题为逐字符阅读 保存到ch-1EOF 的值...
  • numo = numi+8 是我为了检查代码的哪些部分工作而投入的一些恶作剧。 (我很奇怪,但它确实让我知道程序正在读取文件,因为它确实正确显示了输入文件编号,并且它也正确地将一个数字保存到了输出文件中。):D 代码现在可以工作了,非常感谢非常需要解释!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-19
  • 2020-05-11
  • 1970-01-01
相关资源
最近更新 更多