jeudi 5 novembre 2015

How do I format an inputted file in C

Basically I have written a code in C to read a file inputted by the user and it will print this out when running. However, I am trying to get some help on how I can format the text. For example if the text file contained :

my cat has a huge stomach
maybe because 
she is pregnant 
or just fat.  

I want to format this text so that it outputs the line that can contain 60 characters, and if the word cannot fit into that 60 character line it should start on a new line like so:

my cat has a huge stomach maybe because she is pregnant or 
just fat.

.

#include <stdio.h>
#include <stdlib.h>


int main()
{
char ch, file_name[25];
FILE *fp;

printf("Enter the name of file you wish to see\n");
gets(file_name);

fp = fopen(file_name,"r"); // read mode

if( fp == NULL )
{
  perror("Error while opening the file.\n");
  exit(EXIT_FAILURE);
}

printf("The contents of %s file are :\n", file_name);

while( ( ch = fgetc(fp) ) != EOF )
  printf("%c",ch);

fclose(fp);
return 0;
}

Also I heard that you shouldn't really use "gets" to retrieve a file. Similarly, I'm not necessarily saying someone should write the code for me, any advice or websites that can help me out would be appreciated.

Aucun commentaire:

Enregistrer un commentaire