File operations-writing and reading in files.
#include <stdio.h>
int main(int argc, char const* argv[])
{
// creating first file
// storing pointer of start of file
FILE* first_file;
first_file = fopen("test1.txt", "w");
// checking if file is opened correctly
if (first_file == 0)
{
printf("Not able to find file.");
}
else
{
// writes the content in file
fprintf(first_file, "This is first file of c language .\n"); //--------------
char* data = "I am happy to programming file operations .";
fputs(data, first_file); //---------------
// closing file
fclose(first_file);
}
// Reading the file content
first_file = fopen("test1.txt", "r");
char content [50];
int i = 0;
// gets the line or(gets characters upto the index given(-1))
while (fgets(content, 6, first_file) != NULL)
{
printf("\n%d\n", i);
i++;
// fgets(content,50,first_file); //using fgets() function
printf("%s", content);
}
// //printing by using fscanf() function
// while (fscanf(first_file, "%s", content) != EOF) //EOF ==> end of file
// {
// printf("%s\n", content);
// }
// // fscanf(first_file, "%c", content);
// // printf("%c", *content);
fclose(first_file);
return 0;
}
No comments:
Post a Comment