The following are the steps to create a random file and enter a few lines of text in it. You can enter any number of lines as desired; simply type stop, followed by the Enter key, when you are done:
- Define a structure consisting of a string member:
struct data{
char str[ 255 ];
};
- Open a random file in write-only mode and point to it with a file pointer:
fp = fopen (argv[1], "wb");
- The program will terminate if the file cannot be opened in write-only mode:
if (fp == NULL) {
perror ("An error occurred in creating the file\n");
exit(1);
}
- Enter the file contents when prompted and store it into the structure members:
printf("Enter file content:\n");
gets(line.str);
- If the text entered is not stop, the structure containing the text is written into the file:
while(strcmp(line.str, "stop") !=0){
fwrite( &line, sizeof(struct data), 1, fp );
- Steps 4 and 5 are repeated until you enter stop.
- When you enter stop, the file pointed at by the file pointer is closed to release the resources allocated to the file:
fclose(fp);
The createrandomfile.c program for creating a random file is as follows:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
struct data{
char str[ 255 ];
};
void main (int argc, char* argv[])
{
FILE *fp;
struct data line;
fp = fopen (argv[1], "wb");
if (fp == NULL) {
perror ("An error occurred in creating the file\n");
exit(1);
}
printf("Enter file content:\n");
gets(line.str);
while(strcmp(line.str, "stop") !=0){
fwrite( &line, sizeof(struct data), 1, fp );
gets(line.str);
}
fclose(fp);
}
Now, let's go behind the scenes to understand the code better.