Как изменить содержимое в файле? - PullRequest
0 голосов
/ 19 сентября 2019

Я - абсолютный новичок в C. Моя проблема - изменить содержимое в файле.

Я пишу два файла, а затем объединяю содержимое двух файлов в другой файл.Это другой файл, который мне нужно изменить.

что изменить?

Значения myfile1.txt: 199112345671273, а значения myfile2.txt - 24AUS2024MED712.

Файл слияния (myfile3.txt) имеет 19911234567127324AUS2024MED712

. Мне нужно изменить значения myfile2.txt.Я хочу скрыть его значения в звездочке, поэтому при чтении myfile3.txt я получаю следующее

199112345671273 ****************

моя логикаиспорчен.Я просто хочу сохранить оба значения myfile1 и myfile2.затем отобразите myfile3 при условии, что myfile2 должен быть скрыт в звездочке при чтении.

Моя программа write.c - записать данные в два файла

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

#define MAX_SIZE 100

int main (int argc, char **argv) {
    char registration[MAX_SIZE], location[MAX_SIZE], faculty[MAX_SIZE];
    int birthOfYear, birthOfMonth, birthOfDate, layerArch1, layerArch2, levelOfStudy, graduatingYear;

    FILE *fptr, *anotherfptr;
    fptr = fopen("myfile01.txt","w");
    anotherfptr = fopen("myfile02.txt", "w");
    if(fptr == NULL) {
            printf("Error!");   
            exit(1);             
    }

    printf("Enter a registration number (XXXXXX): ");
    scanf("%s", registration); //read as a string

    printf("Enter location (location as in currency, AUS CND SIN: ");
    scanf("%s", location); //read as a string

    printf("Enter faculty (ENG BUS SCI MED): ");
    scanf("%s", faculty); //read as a string

    printf("Enter birth of year (19XX 200X): ");
    scanf("%d", &birthOfYear);

    printf("Enter birth of month (XX): ");
    scanf("%d", &birthOfMonth);

    printf("Enter birth of date (XX): ");
    scanf("%d", &birthOfDate);

    printf("Enter level of study (1 -first, 2- second, 3- third, 4-fourth, 5 - other): ");
    scanf("%d", &levelOfStudy);

    printf("Enter graduating year (XXXX): ");
    scanf("%d",&graduatingYear);

    printf("Enter layer of Architecture 1 (0-sensing, 1-network, 2-smart(hidden), 3-devices): ");
    scanf("%d",&layerArch1);

    printf("Enter layer of Architecture 2 (0-sensing, 1-network, 2-smart(hidden), 3-devices): ");
    scanf("%d",&layerArch2);

    fprintf(fptr,"%d%s%d%d%d", birthOfYear, registration, birthOfMonth, birthOfDate, layerArch1); //writing into file with some formatting 
    fclose(fptr);

    fprintf(anotherfptr,"%d%d%s%d%s%d%d", layerArch2, levelOfStudy, location, graduatingYear, faculty, birthOfDate, birthOfMonth); 
    //writing into file with some formatting

    fclose(anotherfptr);

    return 0;
  }

Моя программа merge.c - объединитьдва файла

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

int main(int argc, char **argv)
{
   FILE *fs1, *fs2, *ft;

   char ch, file1[200], file2[200], file3[200];

   printf("Enter name of first file\n");
   gets(file1);

   printf("Enter name of second file\n");
   gets(file2);

   printf("Enter name of file which will store contents of the two files\n");
   gets(file3);

   fs1 = fopen(file1, "r");
   fs2 = fopen(file2, "r");

   if(fs1 == NULL || fs2 == NULL)
   {
      perror("Error ");
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }

   ft = fopen(file3, "w"); // Opening in write mode

   if(ft == NULL)
   {
      perror("Error ");
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }

   while((ch = fgetc(fs1)) != EOF)
      fputc(ch,ft);

   while((ch = fgetc(fs2)) != EOF)
      fputc(ch,ft);

   printf("The two files were merged into %s file successfully.\n", file3);

   fclose(fs1);
   fclose(fs2);
   fclose(ft);

   return 0;
}

my read.c - для чтения файлов

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

int main(int argc, char **argv) {
    char c[1000];
    FILE *fptr, anotherfptr;

    if ((fptr = fopen("myfile1.txt", "r")) == NULL) {
        printf("Error! opening file");
        exit(1);         
    }

    // reads text until newline 
    fscanf(fptr,"%[^\n]", c);
    printf("Data from the file:\n%s", c);
    fclose(fptr);

    if ((fptr = fopen("myfile2.txt", "r")) == NULL) {
        printf("Error! opening file");
        exit(1);         
    }

    // reads text until newline 
    fscanf(anotherfptr,"%[^\n]", c);
    printf("Data from the file:\n%s", c);
    fclose(anotherfptr);
    return 0;
}

Моя проблема в том, как решить эту простую программу.Я буквально застрял.

Любая помощь / разъяснения будет высоко ценится.

Ответы [ 2 ]

0 голосов
/ 23 сентября 2019

Надеюсь, вы перепробовали все возможные пути.Пожалуйста, проверьте решение ниже:

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

int main(int argc, char **argv) {
char c1[1000];
char c3[1000];
FILE *fptr, *anotherfptr;

if ((fptr = fopen("myfile1.txt", "r")) == NULL) {
    printf("Error! opening file");
    exit(1);
}

// reads text until newline
fscanf(fptr,"%[^\n]", c1);
printf("Data from the file myfile1.txt :%s\n", c1);
fclose(fptr);

//calculate the length of string c1
int lengthc1=strlen(c1);
printf("Length of string c1 is : %d\n", lengthc1);

if ((anotherfptr = fopen("myfile3.txt", "r")) == NULL) {
    printf("Error! opening file");
    exit(1);
}

// reads text until newline
fscanf(anotherfptr,"%[^\n]", c3);
printf("Data from the file myfile3.txt :%s\n", c3);
fclose(anotherfptr);

//to show data of myfile2.txt in astrisk
int lengthc3=strlen(c3);
printf("Final data is ");
for ( int i=0 ; i<=lengthc3 ; i++)
{
    if (i < lengthc1)
    {
            printf("%c", c3[i]);
    }
    else
    {
            printf("*");
    }
}

return 0;
}
0 голосов
/ 19 сентября 2019

В этом случае вам нужно создать программу, которая должна знать содержимое / размер «myfile1.txt» или «myfile2.txt», чтобы отображать * для второго содержимого при чтении «myfile3.txt».

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

Переходя к логике: Маскирование - это то, что вы ищете. В основном оно используется в качестве маскировки пароля.(Возможно, вы видели * при вводе пароля на любом сайте.).В вашем случае вы хотите отображать содержимое как * без фактического изменения содержимого в файле.

Получите представление о том, как делается маскировка для пароля, в следующем документе:

https://www.geeksforgeeks.org/print-in-place-of-characters-for-reading-passwords-in-c/

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