int booksave(void)
{
struct book library[MAXBKS]; /* array of structures */
int count = 0;
int index, filecount;
FILE * pbooks;
int size = sizeof (struct book);
if ((pbooks = fopen("book.txt", "a+b")) == NULL)
{
fputs("Can't open book.txt file\n",stderr);
exit(1);
}
rewind(pbooks); /* go to start of file */
while (count < MAXBKS && fread(&library[count], size,
1, pbooks) == 1)
{
if (count == 0)
puts("Current contents of book.dat:");
printf("%s by %s: $%.2f\n",library[count].title,
library[count].author, library[count].value);
count++;
}
filecount = count;
if (count == MAXBKS)
{
fputs("The book.dat file is full.", stderr);
exit(2);
}
puts("Please add new book titles.");
puts("Press [enter] at the start of a line to stop.");
while (count < MAXBKS && gets(library[count].title) != NULL
&& library[count].title[0] != '\0')
{
puts("Now enter the author.");
gets(library[count].author);
puts("Now enter the value.");
scanf("%f", &library[count++].value);
while (getchar() != '\n')
continue; /* clear input line */
if (count < MAXBKS)
puts("Enter the next title.");
}
if (count > 0)
{
puts("Here is the list of your books:");
for (index = 0; index < count; index++)
printf("%s by %s: $%.2f\n",library[index].title,
library[index].author, library[index].value);
fwrite(&library[filecount], size, count - filecount,
pbooks);
}
else
puts("No books? Too bad.\n");
puts("Bye.\n");
fclose(pbooks);
return 0;
}
开发者ID:tuling56,项目名称:CPP,代码行数:63,代码来源:booksave.c
示例9: init_ram_segments
static void
init_ram_segments(void)
{
int i, errflag;
FILE *iomem;
char buf[BUFSIZE], *p1, *p2;
physaddr_t start, end;
if ((iomem = fopen("/proc/iomem", "r")) == NULL)
goto fail_iomem;
while (fgets(buf, BUFSIZE, iomem)) {
if (strstr(buf, "System RAM")) {
console(buf);
nr_segments++;
}
}
if (!nr_segments)
goto fail_iomem;
ram_segments = (struct ram_segments *)
GETBUF(sizeof(struct ram_segments) * nr_segments);
rewind(iomem);
i = 0;
while (fgets(buf, BUFSIZE, iomem)) {
if (strstr(buf, "System RAM")) {
if (!(p1 = strstr(buf, ":")))
goto fail_iomem;
*p1 = NULLCHAR;
clean_line(buf);
if (strstr(buf, " "))
goto fail_iomem;
p1 = buf;
if (!(p2 = strstr(buf, "-")))
goto fail_iomem;
*p2 = NULLCHAR;
p2++;
errflag = 0;
start = htoll(p1, RETURN_ON_ERROR|QUIET, &errflag);
end = htoll(p2, RETURN_ON_ERROR|QUIET, &errflag);
if (errflag)
goto fail_iomem;
ram_segments[i].start = PHYSPAGEBASE(start);
if (PAGEOFFSET(start))
ram_segments[i].start += PAGESIZE();
ram_segments[i].end = PHYSPAGEBASE(end);
if (PAGEOFFSET(end) == (PAGESIZE()-1))
ram_segments[i].end += PAGESIZE();
console("ram_segments[%d]: %016llx %016llx [%s-%s]\n", i,
(ulonglong)ram_segments[i].start,
(ulonglong)ram_segments[i].end, p1, p2);
i++;
}
}
fclose(iomem);
return;
fail_iomem:
fclose(iomem);
nr_segments = 0;
if (ram_segments)
FREEBUF(ram_segments);
return;
}
/****************************************************************************
* Creator: T. M. Farrington
* Purpose: To search a binary file that contains command syntaxes.
*
* Inputs: One binary file, the name of which is defined in the include file.
* Character pointer to the function name to be looked up.
* Character pointer to a buffer where the full command syntax will
* be placed if it is found.
* Maximum string size that the buffer can receive.
*
* Outputs: Return TRUE if search was successful, FALSE if not.
* If TRUE, places full command syntax in the buffer.
*
****************************************************************************/
int W_EXPORT KpeGetKALHelp(LPSTR fnameptr, LPSTR buffer, int maxsiz)
{
FILE *finptr;
int iFile;
OFSTRUCT of;
char pFullPath[FILENAME_MAX];
unsigned short csfname = lstrlen(fnameptr) + 1;
unsigned short ssfname, ssrecord;
unsigned short found = FALSE;
/* First look for the file in KAPPA's system directory. *
* If not there, then use the PATH. */
KppGetSystemDirectory(pFullPath, FILENAME_MAX);
strncat(pFullPath, binary_file, FILENAME_MAX - strlen(pFullPath) - 1);
if ((iFile = OpenFile(pFullPath, &of, OF_READ)) == -1)
iFile = OpenFile(binary_file, &of, OF_READ);
if ((iFile == -1) || ((finptr = fdopen(iFile, "rb")) == NULL))
{
RegisterKappaMessage(IDE_FCANTOPEN,
KppAddAtom(binary_file), NULLID, NULLID);
KppIncrementPopupCountCB(EDITW);
PostKappaMessage();
KppDecrementPopupCountCB(EDITW);
return FALSE;
}
rewind(finptr);
/* While not found, get the two string length values (2 bytes each)
* at the begining of the record.
*/
while (!found)
{
fread(&ssfname, 2, 1, finptr);
if (feof(finptr))
break;
fread(&ssrecord, 2, 1, finptr);
if (feof(finptr))
break;
/* If the size of the parameter function name ==
* size of the scanned function name,
*/
if (csfname == ssfname)
{
char data[MAX_RECORD_LENGTH];
/* then read the function name and if the strings match, */
if ((fread(data, ssfname, 1, finptr) != NULL) &&
(!lstrcmp(fnameptr, data)))
{
/* get the rest of the record and concatenate both strings
into the output file,
RBP: Do not concatenate */
/* kstrcpy (buffer, data, maxsiz); */
if (fread(data, ssrecord - ssfname - 4, 1, finptr) != NULL)
_fstrncpy(buffer, data, maxsiz);
/* Stop the search. */
found = TRUE;
}
else
/* otherwise advance the file pointer to the next record.*/
fseek(finptr, (long) ssrecord - 4 - ssfname, SEEK_CUR);
}
else /* otherwise advance the file pointer to the next record. */
fseek(finptr, (long) ssrecord - 4, SEEK_CUR);
}
fclose(finptr);
if (!found && (KppGetKalFunctionSyntaxCB(KppCheckAtom(fnameptr),
buffer, maxsiz) != -1 ||
KppGetDLLFunctionSyntax(fnameptr, buffer, maxsiz) != -1))
found = TRUE;
return found;
}
/*Initial run, read in given file and save sorted blocks to temporary files*/
BOOLEAN initialRun(char * filePath, int bufferMemoryCount, Schema * schema, FileList * fileL, int * totalRecordCount){
FILE * initialFP;
char line[LINE_LENGTH];
char * tokenPtr;
int i;
/*Open path file*/
if((initialFP = fopen(filePath,"r")) == NULL){
fprintf(stderr, "Error: Failed to open file %s\n",filePath);
return FALSE;
}
/*Determine and set type of file data*/
/*Get first line of file and count number of ','*/
fgets(line, LINE_LENGTH, initialFP);
/*rewind to start of file for future use*/
rewind(initialFP);
/*Determine first occurrence of ',' in line*/
tokenPtr = strchr(line,',');
/*Determine if there is a second occurrence of ',' in line*/
tokenPtr = strchr(tokenPtr+1,',');
/*if NULL then file contains guild records*/
/*(since there is only 1 ',' for every guild file line)*/
if(tokenPtr == NULL)
*schema = GUILD;
/*else then file contains character records*/
else
*schema = CHARACTER;
/*While there is still more of the file to read*/
while (line[0] != '\0'){
FILE * tempFP;
int recordCount = bufferMemoryCount;
Record * records = calloc(bufferMemoryCount, sizeof(Record));
if (!records){
fprintf(stderr, "Error: Failed to allocate memory for records\n");
return FALSE;
}
for(i = 0; i < bufferMemoryCount; i++){
char * tempString = NULL;
/*If reached end of file*/
if(fgets(line, LINE_LENGTH, initialFP) == NULL){
/*set record size to index reached*/
recordCount = i;
line[0] = '\0';
break;
}
if(*schema == CHARACTER){
strcpy(records[i].field.character.cname,strtok(line,","));
tempString = strtok(NULL,",");
records[i].field.character.team = (unsigned short int) strtoul(tempString, NULL, 0);
tempString = strtok(NULL,",");
records[i].field.character.level = (unsigned short int) strtoul(tempString, NULL, 0);
tempString = strtok(NULL,",");
records[i].field.character.cid = (unsigned int) strtoul(tempString, NULL, 0);
tempString = strtok(NULL,",");
records[i].GuildID = (unsigned int) strtoul(tempString, NULL, 0);
}
else{ /*If GUILD schema*/
int lineLen = strlen(line);
/*Remove new line from end of string*/
if (lineLen > 0 && line[lineLen-1] == '\n')
line[lineLen-1] = '\0';
tempString = strtok(line,",");
records[i].GuildID = (unsigned int) strtoul(tempString, NULL, 0);
strcpy(records[i].field.g_name,strtok(NULL,","));
}
*totalRecordCount = *totalRecordCount +1;
}
/*Sort the blocks*/
quickSort(records, 0, recordCount-1);
/*insertionSort(records, recordCount);*/
/*Write out buffers run of B blocks to temp files*/
/*create temporary file*/
if((tempFP = tmpfile()) == NULL){
fprintf(stderr, "Error: Failed to create temporary file\n");
return FALSE;
}
/*Write array of records to binary file*/
fwrite(records, sizeof(Record), recordCount, tempFP);
/*no need to loop through records array*/
/*for (i = 0; i < recordCount; i++){
fwrite(&records[i], sizeof(Record), 1, tempFP);
}*/
/*Rewind temp file pointer for later merging*/
rewind(tempFP);
/*add file pointer to file list*/
addFile(fileL, tempFP);
//.........这里部分代码省略.........
//.........这里部分代码省略.........
addRecord(&bufferNodes[outputBuffIndex],
minIndex.buff->pageRecords[minIndex.pgIndex], pagesize, bufferNodes[outputBuffIndex].recordCount);
/*remove the same record from original buffer*/
removeRecord(minIndex.buff, minIndex.pgIndex);
/*if output buffer is full, write page to file*/
if(bufferNodes[outputBuffIndex].recordCount == pagesize){
/*write page to file*/
int written;
written = fwrite(bufferNodes[outputBuffIndex].pageRecords, sizeof(Record),
pagesize, outputFile);
if(written !=pagesize){
fprintf(stderr, "Error: Failed to write to output file, wrote %i records\n",written);
return FALSE;
}
/*clear page in output buffer*/
clearPage(&bufferNodes[outputBuffIndex], pagesize);
}
/*if original buffer is empty, read in another page*/
if(minIndex.buff->recordCount == 0){
int recordPageIndex;
/*fill buffer with records from file*/
for(recordPageIndex = 0; recordPageIndex < pagesize; recordPageIndex++){
Record record;
if(minIndex.buff->fileNode->fp != NULL){
if(fread(&record, sizeof(Record), 1, minIndex.buff->fileNode->fp) == 1){
/*add record to page (records array)*/
if(addRecord(minIndex.buff, record, pagesize, recordPageIndex) == FALSE)
return FALSE;
/*add record index to heap*/
if(addToHeap(&rHeap, minIndex.buff, recordPageIndex) == FALSE)
return FALSE;
}
/*else reached file end*/
else{
/*temp file will be automatically deleted by the system*/
fclose(minIndex.buff->fileNode->fp);
minIndex.buff->fileNode->fp = NULL;
/*removeFile(currentFiles, minIndex.buff->fileNode);*/
break;
}
}
}
}
/*if buffer is still empty, then 0 records were read in,
therefore file is empty and the buffer is now free*/
if(minIndex.buff->recordCount == 0)
/*decrement buffers in use counter*/
buffersInUse--;
}
/*All files for run have been fully read*/
/*Write out records still in output buffer*/
if(bufferNodes[outputBuffIndex].recordCount > 0){
/*Output buffer page was not full*/
int i = 0;
for(i = 0; i < pagesize; i++){
if(bufferNodes[outputBuffIndex].pageRecords[i].GuildID != 0){
fwrite(&bufferNodes[outputBuffIndex].pageRecords[i],
sizeof(Record), 1, outputFile);
removeRecord(&bufferNodes[outputBuffIndex], i);
}
}
}
/*Rewind outfile for future merge*/
rewind(outputFile);
runCount++;
}
/*set runFileListas new current file list*/
freeFileNode(¤tFiles);
currentFiles = runFileList;
*passes = *passes+1;
*runs = *runs + runCount;
printf("Pass %i resulted in %i runs\n",*passes,runCount);
}
/*FileList will contain link to only 1 temporary binary file*/
if(currentFiles.fileCount != 1){
fprintf(stderr, "Error: Number of files:%i is invalid\n",currentFiles.fileCount);
return FALSE;
}
*sorted = currentFiles.fileHeadNode->fp;
/*free allocated memory*/
for(bufferIndex = 0; bufferIndex < availableBuffers; bufferIndex++){
freeBuffer(&bufferNodes[bufferIndex]);
}
free(bufferNodes);
freeHeap(&rHeap);
freeFileNode(¤tFiles);
/*free(currentFiles);*/
return TRUE;
}
// Calling this function will generate a public and private key and store them in the pointers
// it is given.
void rsa_gen_keys(struct public_key_class *pub, struct private_key_class *priv, char *PRIME_SOURCE_FILE)
{
FILE *primes_list;
if(!(primes_list = fopen(PRIME_SOURCE_FILE, "r"))){
fprintf(stderr, "Problem reading %s\n", PRIME_SOURCE_FILE);
exit(1);
}
// count number of primes in the list
long long prime_count = 0;
do{
int bytes_read = fread(buffer,1,sizeof(buffer)-1, primes_list);
buffer[bytes_read] = '\0';
for (i=0 ; buffer[i]; i++){
if (buffer[i] == '\n'){
prime_count++;
}
}
}
while(feof(primes_list) == 0);
// choose random primes from the list, store them as p,q
long long p = 0;
long long q = 0;
long long e = powl(2, 8) + 1;
long long d = 0;
char prime_buffer[MAX_DIGITS];
long long max = 0;
long long phi_max = 0;
srand(time(NULL));
do{
// a and b are the positions of p and q in the list
int a = (double)rand() * (prime_count+1) / (RAND_MAX+1.0);
int b = (double)rand() * (prime_count+1) / (RAND_MAX+1.0);
// here we find the prime at position a, store it as p
rewind(primes_list);
for(i=0; i < a + 1; i++){
// for(j=0; j < MAX_DIGITS; j++){
// prime_buffer[j] = 0;
// }
fgets(prime_buffer,sizeof(prime_buffer)-1, primes_list);
}
p = atol(prime_buffer);
// here we find the prime at position b, store it as q
rewind(primes_list);
for(i=0; i < b + 1; i++){
for(j=0; j < MAX_DIGITS; j++){
prime_buffer[j] = 0;
}
fgets(prime_buffer,sizeof(prime_buffer)-1, primes_list);
}
q = atol(prime_buffer);
max = p*q;
phi_max = (p-1)*(q-1);
}
while(!(p && q) || (p == q) || (gcd(phi_max, e) != 1));
// Next, we need to choose a,b, so that a*max+b*e = gcd(max,e). We actually only need b
// here, and in keeping with the usual notation of RSA we'll call it d. We'd also like
// to make sure we get a representation of d as positive, hence the while loop.
d = ExtEuclid(phi_max,e);
while(d < 0){
d = d+phi_max;
}
printf("primes are %lld and %lld\n",(long long)p, (long long )q);
// We now store the public / private keys in the appropriate structs
pub->modulus = max;
pub->exponent = e;
priv->modulus = max;
priv->exponent = d;
}
请发表评论