I try to create a text file, and with the help of a random letter generator (+ space, in order to get "words" of different lengths) write to this file a set of these letters. Separately, if I do, the file is created, the letters are generated, and together this cannot be done. You can explain why and set on the right path)

#include <cstdio> #include <cstdlib> #include <ctime> int main () { FILE * pFile; int val = 15*1024*1024; int i; srand(time(NULL)); unsigned char mass; for(i=0;i<30;++i) mass=(rand() % ('z'-'a'+1))+'a'; pFile = fopen ( "myf.txt" , "w" ); fwrite (mass , 1 , sizeof(val) , pFile ); fclose (pFile); } 

And another question: How can you fill the file with random letters with a space (so that you get "words") at 10MB?

    2 answers 2

    So,

     for(i=0;i<30;++i) mass=(rand() % ('z'-'a'+1))+'a'; 

    30 times we reassign the value of the same variable (by the way, the space here does not smell).

    Then write to the file 4 bytes ( int size)? located at the address stored in the mass variable:

     fwrite (mass , 1 , sizeof(val) , pFile ); 

    By the way, this line is not compiled in C ++, so ...

    Probably. did you want something like this?

     #include <cstdio> #include <cstdlib> #include <ctime> int main () { FILE * pFile; pFile = fopen ( "myf.txt" , "w" ); int val = 15*1024*1024; int i; srand(time(NULL)); char mass; for(i=0; i<val; ++i) { mass=(rand() % ('z'-'a'+2))+'a' - 1; if (mass < 'a') mass = ' '; fwrite (&mass , 1 , sizeof(mass) , pFile ); } fclose (pFile); } 

      A tick had time to appear .. but oh well, in vain, I wrote something, it would also come in handy.

       #include <ctime> #include <fstream> int main() { //Задаём диапазон количества символов в одном слове и количество символов в файле const int minWordLength = 2, maxWordLength = 30, maxSymbolInFile = 10*1024*1024; std::ofstream fout("out.txt"); srand(time(nullptr)); //определяем длину первого слова int currentWordLength = minWordLength + rand() % (maxWordLength - minWordLength); int symbolsInFile = 0; while (symbolsInFile<maxSymbolInFile) { if (!currentWordLength) { //Если завершили формирования слова, то печатаем пробел и fout << " "; ++symbolsInFile; //определяем длину следующего слова currentWordLength = minWordLength + rand() % (maxWordLength - minWordLength); } //Добавляем в текущее слово новый символ fout << (char)((rand() % ('z' - 'a' + 1)) + 'a'); --currentWordLength; ++symbolsInFile; } fout.close(); } 
      • If you tell us what is happening in your code, the checkmark may move. Well, or at least the pros will appear. The code without explanations is not very helpful in learning. - Nick Volynkin
      • There, in fact, almost the same as in the example of the author of the question. But why not add comments to the code. - slav-yrich
      • Thanks, that's better. (Plus for the first time) - Nick Volynkin