- Open a sequential file in write-only mode and point to it with a file pointer:
fp = fopen (argv[1], "w");
- Enter the content for the file when prompted:
printf("Enter content for the file ");
gets(str);
- Enter stop when you are done entering the file content:
while(strcmp(str, "stop") !=0)
- If the string you entered is not stop, the string is written into the file:
fputs(str,fp);
- Close the file pointer to release all the resources allocated to the file:
fclose(fp);
The createtextfile.c program for creating a sequential file is as follows:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void main (int argc, char* argv[])
{
char str[255];
FILE *fp;
fp = fopen (argv[1], "w");
if (fp == NULL) {
perror ("An error occurred in creating the file ");
exit(1);
}
printf("Enter content for the file ");
gets(str);
while(strcmp(str, "stop") !=0){
fputs(str,fp);
gets(str);
}
fclose(fp);
}
Now, let's go behind the scenes to understand the code better.