Проблема с чтением и записью массива из файла в C в версии указателя программы - PullRequest
1 голос
/ 14 апреля 2020

У меня есть задача. Я должен написать программу, которая читает из файла и записывать в другой файл и копировать массив. Я должен использовать указатели. Это моя программа

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

int _strlen (char *array)   // here I check array length
{
    int i;
    for (i = 0; array[i] != '\0'; ++i);    
    return i;   
}

int writeText(FILE *wp, char *s)
{
    int sum = 0;
    while((*s++ = fputc(*s, wp)))
    {
        sum++;
    }
    return sum;   //I must return array length in my task, so I choose sum to  count how many signs I put
}


int readText(FILE *wp, char *s, int max)
{
    int sum = 0;

    while((*s++ = fgetc(wp)) != EOF)
    {
        sum++;
    }
    return sum;  //I must return array length in my task, so I choose sum to  count how many signs I get
}

int copyText (char *s, char *t, int max)  
{
    if (_strlen(t) > max)
    {
        printf("This array is too big.");
    }
    else
    {
        while((*t++ = *s++));
    }
    return _strlen(t);  //I must return array length in my task
}


int main (int argc, char *argv[])
{
    int c, i; 
    char *s, *t, *r;  
    FILE *wz, *wc;                         
    char arr[10000];
    s = arr;
    char copyArr[10000];    
    t = copyArr;
    char keyArr[10000]; 
    r = keyArr;

    if (argc != 3) {                                
    printf("Wrong arguments number\n");
    printf("I should run this way:\n");
    printf("%s source result\n",argv[0]);
    exit(1);
    }

    if( (wz= fopen(argv[1],"r")) == NULL) {
        printf("Open error %s\n", argv[1]);
        exit(1);
    }
    if( (wc= fopen(argv[2], "w")) == NULL) {
        printf("Open error %s\n", argv[2]);
        exit(2);
    }

    fprintf(wc, "Write text from file source.txt:\n");
    readText(wz, s, 10000);   
    writeText(wc, s); 

    fprintf(wc, "\nCopy and paste array:\n\n");
    copyText(t, s, 10000);         //robie kopie tablicy
    writeText(wc, t);                    //wypisuje ją

    return 0;
}    

Это мой входной файл

A computer is a machine that can be instructed to carry out sequences of arithmetic or logical operations 
automatically via computer programming. Modern computers have the ability to follow generalized sets of 
operations, called programs. These programs enable computers to perform an extremely wide range of tasks. 

Это неверный вывод

Write text from file source.txt:
A computer is a machine that can be instructed to carry out sequences of arithmetic or logical operations 
automatically via computer programming. Modern computers have the ability to follow generalized sets of 
operations, called programs. These programs enable computers to perform an extremely wide range of tasks. 
\FF\00
Copy and paste array:

\00

Ожидаемый вывод

Write text from file source.txt:
A computer is a machine that can be instructed to carry out sequences of arithmetic or logical operations 
automatically via computer programming. Modern computers have the ability to follow generalized sets of 
operations, called programs. These programs enable computers to perform an extremely wide range of tasks. 

Copy and paste array:
A computer is a machine that can be instructed to carry out sequences of arithmetic or logical operations 
automatically via computer programming. Modern computers have the ability to follow generalized sets of 
operations, called programs. These programs enable computers to perform an extremely wide range of tasks. 

Вы запускаете программу таким образом: копирование массива. Я попробовал это решение, но оно не сработало.

int copyText (char *s, char *t, int max)  
{
    if (_strlen(t) > max)
    {
        printf("This array is too big.");
    }
    else
    {
        while( (*s++ = *t++) != '\0');
    }

    return _strlen(t);  //I must return array length in my task
}

1 Ответ

1 голос
/ 14 апреля 2020

Проблемы с вашим кодом следующие:

  • В функции readText() вы также читаете символ EOF из файла (из-за приоритета операций вы сначала присваиваете значение (т. е. (*s++ = fgetc(wp))) и сравнивая его потом с EOF. Простой способ избежать этого без изменения кода - заменить значение EOF на конец строкового символа '\ 0';
  • В функции writeText() вам следует прекратить запись символов после окончания строки, чтобы избежать записи в файл любого «мусора», находящегося в памяти.

В коде:

int readText(FILE *wp, char *s, int max)
{
    int sum = 0;

    while((*s++ = fgetc(wp)) != EOF)
    {
        sum++;
    }
    *(s-1)='\0'; // replace EOF by empty character
    return sum;
}

...

int writeText(FILE *wp, char *s)
{
    int sum = 0;
    while((*s++ = fputc(*s, wp)))
    {
        sum++;

        if(*s == '\0')
            break;

    }
    return sum;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...