File IO and Bit Manipulation Homework - Text file
Find the Average of 3 Numbers stored in a text file and then write the numbers and their average to a text file. Then, on the screen, display one of the numbers as a normal integer, and what that integer would be with its bits shifted one to the left.
Write a program that will ask the user for a file name. Contained in this file is a series of 3 integers separated by white space. Read in the 3 numbers. Add them up and then calculate their average.
Then write the three numbers and average to one row in a new text file with semicolons separating them.
Now do work on the screen (using printf) with one of the numbers.
Then display one of the three numbers on the screen in both decimal and hex format (%d and %x).
Then move the bits of your average integer over one place ot the left (<<=1) and display that new shifted number in both decimal and hex format (%d and %x).
Steps:
You can start with the sample simplewrite.c program. It appears at the bottom of this assignment. Compile the sample and run it. You will need to create a file1.txt with 2 integers, separated by spaces. After running the program, you can look at file2.txt to see that it is filled with those same numbers plus the sum.
To adjust this program to handle the job of this assignment:
1) Change your file1.txt file to include one more integer on each row
2) Change the program to parse one additional integer. sscanf is the command that parsed the integers.
3) Change the program to calculate the average of those 3 integers. The average should be a float or double.
4) Change the program to write the extra integer and the average, and not to write the sum as it had before.
5) Change the write statement to insert a semi-colon instead of a space between each number.
6) Compile and run to verify that the 3 numbers are being written in file2.txt with their average. If needed, use gdb to debug to see where your program is crashing. Note: If you get odd results for reading values, please be sure you do not have a \r carriage return in your file. You can remove \r using notepad++'s edit / EOL Conversion / Unix. Here is a helpful debugger tutorial: http://www.cs.swarthmore.edu/~newhall/unixhelp/howto_gdb.html
7) Print any one of the integers you read to the screen using printf. Print it once in %d integer format and another time as %x hex format.
8) Move the bits of that one number by using the << operator.
9) Repeat step 7 to show what the number looks like with its bits shifted.
#include <stdio.h>
#include <string.h>
int main(void){
FILE * inp;
FILE * outp;
char * myfile = "file1.txt";
char * myfileout = "file2.txt";
inp = fopen(myfile, "r");
outp = fopen(myfileout, "w");
if (inp == NULL || outp == NULL) {
puts("error opening") ;
return 1;
}
char str[51];
int x, y;
if ( fgets(str,50,inp) != NULL ) {
if (sscanf(str,"%d %d",&x,&y) != 2)
puts("error extracting");
int z = x + y;
if (fprintf(outp,"%d,%d,%d\n",x,y,z)< 0){
puts ("error writing");
}
}
}