In: Computer Science
Take the Java program Pretty.java and convert it to the equivalent C program. You can use the file in.txt as sample input for your program.
v import java.io.*; import java.util.*; public class Pretty { public static final int LINE_SIZE = 50; public static void main(String[] parms) { String inputLine; int position = 1; Scanner fileIn = new Scanner(System.in); while (fileIn.hasNextLine()) { inputLine = fileIn.nextLine(); if (inputLine.equals("")) { if (position > 1) { System.out.println(); } System.out.println(); position = 1; } else { if ((position+inputLine.length()-1) > LINE_SIZE) { System.out.println(); position = 1; } System.out.print(inputLine); position += inputLine.length(); if (position <= LINE_SIZE) { // add a blank after the current word System.out.print(" "); position++; } } } } }
Take input file as in.txt :
sknkbakbhbhkabbkbsbak nsjbnkjb kabkhb bkebkb
jwbkb wsb hkws bswb bkbse nkbs bekb bejkbk ebkhb jksebkjb bsekb hesbhb hbeshkb hbeskhb hksebvhkbsk esbhkb hbheb
jksbwb bkbk kjbkjbk
sjkbkeb nejkbnkb jbekjb
enkbk kjebske jbkwhebsk
kbshjb
ebhbk
C program :
#include <stdio.h>
#include <string.h>
#define LINE_SIZE 50
int main(int argc, char* argv[])
{
FILE* file = fopen("in.txt", "r"); // reading the input file in.txt
char line[1000000]; // char array to store content in lines
int position = 1; // set position to 1
while (fgets(line, sizeof(line), file)) // runs while loop until all the content of file is read
{
if(strcmp(line,"")==0) // if the line in a file is empty
{
if(position > 1) // if position is greater than 1 print a new line
{
printf("\n");
}
printf("\n");
position =1; // set the position as 1
}
else // if line in a file is not empty
{
if((position + sizeof(line)-1) > LINE_SIZE) // if condition is true
{
printf("\n"); // print a new line
position = 1; // set position =1
}
printf("%s",line); // print the current line
position += sizeof(line); // sizeof is used to calculate length of the line
if(position <= LINE_SIZE)
{
printf(" ");
position++;
}
}
}
fclose(file); // close the file
return 0;
}
Screenshot and Output :