Без переписывания файла, желательно используя ресурсы языка Си, ну или системные вызовы Linux, как перезаписать строкой начало файла, оставив его остальную часть как есть?
прочитать содержимое файла куда-нить, затем добавить в начало нужную строку, а затем дописать пробыкапленные данные.
а, вообще, это дело sed'а: sed -i '1s/^/sometext\n/' somefile
Так #перезаписать" или "вставить"? Первое тривиально, второе потребует перезаписи всего файла (хотя весь его бэкапить в другое место не нужно, просто, начиная с конца, "отодвигать" по кускам на нужное расстояние).
записать или вставить ? записать легко - сделать seek() на начало файла, второе без сдвига - перезаписи никак увы - невозможно в принципе на существующих ОС.
>IMO феерический бред.
Эх, не работали вы с Си++ во времена BC++3.1 или Watcom 9 :)
Действительно, сейчас позиционирование в конец не нужно, а append
вообще не позволяет переписывать исходный контент.
Тогда просто непонятно, в чём проблема. На тесте всё работает отлично:
#include <stdio.h>
int main(void)
{
FILE *fp = fopen("test", "wb");
fputs("0123456789", fp);
fclose(fp);
fp = fopen("test", "r+b");
fseek(fp, 0, SEEK_SET);
fputs("abc", fp);
fclose(fp);
return 0;
}
> Эх, не работали вы с Си++ во времена BC++3.1 или Watcom 9 :)
> Действительно, сейчас позиционирование в конец не нужно, а append
> вообще не позволяет переписывать исходный контент.
Что значит "сейчас"?
Интересно когда (и в каких Unix системах) такое позиционирование
было необходимо в данном конкретном случае?
я открывал файл в режиме "w" а не "r+", потому и конец записываемой строки обрезал файл.
----------------------------------
На эту тему доштудировал ман-страницу по fopen:
The argument mode points to a string beginning with one of the following sequences (Addi- tional characters may follow these sequences.):
r Open text file for reading. The stream is positioned at the beginning of the file.
r+ Open for reading and writing. The stream is positioned at the beginning of the file.
w Truncate file to zero length or create text file for writing. The stream is posi- tioned at the beginning of the file.
w+ Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
a Open for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at the end of the file.
a+ Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.
The mode string can also include the letter ``b'' either as a last character or as a charac- ter between the characters in any of the two-character strings described above. This is strictly for compatibility with C89 and has no effect; the ``b'' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the ``b'' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-Unix environments.)