求大神帮忙写一段代码参考,原理会,但是刚开始上课,不会写代码
RequirementsA signature is used to validate the contents of a file. The algorithm to calculate the signature is
the objective of this lab assignment.
IMPORTANT!!
Implement the algorithm exactly as described below. Points will be deducted if your code
implements a different technique for calculating the code.
Write two functions called getCode( ) and testValidity( ):
Characteristics of getCode( ):
1. Function signature: uint32 getCode(char *file, int count)
2. Two parameters: file name & a count of the number of bytes in a file.
3. Cycle through a file, e.g., fileA, and put them into 32-bit chunks.
4. Using one’s complement arithmetic, add the 32-bit chunk with the next 32-bit chunk of the file,
checking for overflow that you need to handle, until fileA is exhausted.
5. Returns a 32-bit one’s complement of that total, i.e., TOGGLE all bits of the final total and
return the code.
Characteristics of testValidity( ):
1. Function signature: bool testValidity(char *newfile, uint32 codeA)
2. Takes two parameters:
a. A new file, call it fileB, and
b. the 32-bit code you just generated with getCode for fileA, e.g., codeA
3. Run getCode on fileB, to get a new code, e.g., codeB.
4. Add codeA and codeB using one’s complement addition.
5. If the result is all 1’s (-0 in 1's complement arithmetic), then the file is valid, i.e., they have the
same contents. Otherwise, they are different files altogether.Code Template
typedef unsigned short ushort;
typedef unsigned int uint32;
typedef unsigned long uint64;
/* send file in → 32-bit code returned */
uint32 getCode(char *file, int count) {
/* count = byte count */
char *buffer; /* put 32-bits of file in a buffer */
register uint64 total=0;
while (count--) {
: :
}
return ??? ; /* one’s complement of the total */
}
/* send file and some code in → returns true if getCode of the file == some code sent in as argument */
bool testValidity(char *newfile, uint32 someCode){
:
return (getCode(newfile, count)== someCode);
}
int main(...) {
:
/* - ask filename from user and put file contents in a buffer and update the count of bytes/words.
- call getCode()function to calculate code using one's complement.
*/
getFname(...); // assigned to fd called infile
: :
code = getCode(infile,count);
/* use code to validate another user-specified file:
* get new file, calculate code and see if they match. If both codes match, then they are have the same contents */
testValidity(infile, code);
}
Sample Output dialog
Enter filename: fileA
Calculated code: 6ae93ff8 (in hex)
Enter another filename for validation: fileB
Validation: Fail → files have different contents
Again? Y
Enter another filename to compare with fileA: fileC
Validation: Success! They have the same contents
Again? N