Home | Computer Science

C File Handling

Program

Write a program using fopen function to create file

        

Program
INPUT

int main() {
  FILE *fptr;

  // Create a file on your computer (filename.txt)
  fptr = fopen("filename.txt", "w");

  // Close the file
  fclose(fptr);

  return 0;
}
                


Program

Write a program use of to write in file\n

            

Program
INPUT

FILE *fptr;

// Open a file in writing mode
fptr = fopen("filename.txt", "w");

// Write some text to the file
fprintf(fptr, "Some text");

// Close the file
fclose(fptr);
                    


Program

Write a program using fopen function to read file

            

Program
INPUT

FILE *fptr;

// Open a file in read mode
fptr = fopen("filename.txt", "r");

// Store the content of the file
char myString[100];

// If the file exists
if (fptr != NULL) {
  // Read the content and print it
  while (fgets(myString, 100, fptr)) {
    printf("%s", myString);
  }
} else {
  printf("Not able to open the file.");
}

// Close the file
fclose(fptr);