发一道新加坡国大的编程作业
发一道新加坡国大的编程作业,挑战的,请进来。LABORATORY EXERCISE (Lab-II)1
Lab-II A: File reading and writing
Problem Statement: Consider a N x N matrix of random
numbers in the range 0 to 99. Write a random number
generator to generate a matrix of N x N (you can fix N in
the range 10 to 20) and write the matrix into a TEXT file –
call this matrix as MatrixA.txt. Read MatrixA.txt from your
program and replace all prime numbers with 0. Write your
output to another file OutputMatrix.txt. You should display
the following output:
============
MatrixA and OutputMatrix from MatrixA.txt and
OutputMatrix.txt files. (Lab Demonstrators will look for
these two files generated by your program automatically).
Number of Prime numbers: 23
=================
NOTE: Following information may be useful. Parts of the codes to read and
write to a file are given below. This is only one way and there are many
ways you may wish to write.
Input file looks like this:
First create files “MatA.txt” and MatB.txt”. Enter the values for a M=4, N=5
(4 x 5) matrix. Follow the style of arranging the numbers given in the
following sampleMatrix.txt file below.
sampleMatrix.txt:
Note - First two lines indicate the number of rows and number of
columns
=======
4
5
2 2 3 4 6
1 2 5 7 3
3 6 1 8 0
10 1 3 7 2
======
Code for reading a single (first) character from a file:
/*Declare a file pointer to sampleMatrix.txt*/
FILE *myFile;
/*number to be input*/
int ip;
/*Open the file for reading*/
myFile = fopen("sampleMatrix.txt","r");
/*Read the first integer, 4, to ip*/
fscanf(myFile,"%d", &ip);
/*close the file stream*/
fclose(myFile);
Code for writing a single character to a file:
/*Declare a file pointer*/
FILE *myFile;
/*Open the file for writing*/
myFile = fopen("output.txt","w");
/*Write a number*/
fprintf(myFile, "%d", 4);
/*close the file stream*/
fclose(myFile);