For example, the file 1.txt contains the information "123456789 * *" How to remove asterisks? At the end should be "123456789".
How to edit a 1.txt file correctly without creating another file?
Open two streams (one read, another write (on update)) to the same file. Overwrite characters not equal to '*', then trim the file.
#include <stdio.h> #include <stdlib.h> #include <errno.h> main (int ac, char *av[]) { if (ac < 2) { printf ("No filename\n"); exit(1); } int i = 0, c; FILE *in = fopen(av[1],"r"), *out = fopen(av[1],"r+"); if (in == NULL || out == NULL) { perror (av[1]); exit(2); } rewind(out); while ((c = fgetc(in)) != EOF) { if (c != '*') { i++; fputc(c,out); } } fclose(in); ftruncate(fileno(out),i); fclose(out); }
To edit a text file that requires changing its size, there is no other way to create a new text file. Specifically for the case with asterisks, you can open the file in read-write mode, read each character and if it is an asterisk, rewrite it with some unreadable character.
like this:
char s[1111]; //исходная строка char ans[1111]; // полученная строка int c = 0; // количество символов в полученной строке //Вставьте код: открытие 1.txt на чтение scanf("%s", &s); for (int i = 0; i < strlen(s); i++) if (s[i] != '*') ans[c++] = s[i]; //Вставьте код: закрытие файла 1.txt //Вставьте код: открытие 1.txt на запись printf("%s", ans); //Вставьте код: закрытие файла 1.txt.
#include <iostream> #include <fstream> using namespace std; int main() { ifstream f("file.txt"); ofstream f0("file.txt"); char s[10]; f >> s; f0 << s; return EXIT_SUCCESS; }
Source: https://ru.stackoverflow.com/questions/13169/
All Articles