Here, we have a basic program example to create and store information in a file using different languages. This program is created in c language, c++, Java, and Python.
Program to create and store a text file in C language
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[1000];
FILE *fptr;
char fname[20]="test.txt";
fptr=fopen(fname,"w");
if(fptr==NULL)
{
printf(" Error in opening file!");
exit(1);
}
printf(" Input a sentence for the file : ");
fgets(str, sizeof str, stdin);
fprintf(fptr,"%s",str);
fclose(fptr);
printf("\n The file %s created successfully...!!\n\n",fname);
return 0;
}
Program to create and store a text file in C++ language
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream file;
file.open ("test.txt");
cout<<"File created.";
file << "This text will be saved into the file.\n";
file.close();
return 0;
}
Program to create and store a text file in Python language
from pathlib import Path
dir_path = Path('Desktop')
file_name = "test.txt"
file_path = dir_path.joinpath(file_name)
if dir_path.is_dir():
with open(file_path, "w") as f:
f.write("This text is written with Python.")
print('File was created.')
else:
print("Directory doesn\'t exist.")
Program to create and store a text file in Java language
import java.io.FileOutputStream;
import java.util.Scanner;
public class FileCreate
{
public static void main(String[] args)
{
try
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name: ");
String name = sc.nextLine();
FileOutputStream fos = new FileOutputStream(name, true);
System.out.print("Enter File Content: ");
String str = sc.nextLine() + "\n";
byte[] b = str.getBytes();
fos.write(b);
fos.close();
System.out.println("file saved.");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}