我正在为学校制作一个程序,我有一个多进程程序,每个进程读取一个文件的一部分,它们一起工作来计算文件中的单词数.我有一个问题,如果有超过2个进程,那么所有进程在读取文件的部分之前从文件中读取EOF.这是相关的代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char *argv[]) {
FILE *input_textfile = NULL;
char input_word[1024];
int num_processes = 0;
int proc_num = 0; //The index of this process (used after forking)
long file_size = -1;
input_textfile = fopen(argv[1], "r");
num_processes = atoi(argv[2]);
//...Normally error checking would go here
if (num_processes > 1) {
//...create space for pipes
for (proc_num = 0; proc_num < num_processes - 1; proc_num++) {
//...create pipes
pid_t proc = fork(); …Run Code Online (Sandbox Code Playgroud) 我通过将字节复制到动态数组,将文件读入C中的内存.目前,每次新字节进入时,我realloc()大一个字节.这似乎效率低下.
有些人建议(我不记得在哪里)每次需要更多的内存是好的,因为它是O(log n)分配时间,只有不到一半的内存未使用的最坏情况.
关于内存分配的任何建议?
任务是将二进制文件解析到内存中.但是,我不知道分配所需的内存量.
哪种方法更可取:在解析例程中进行多个小malloc,或者首先遍历文件以确定所需的内存量,然后再次解析?
任何提示都表示赞赏.
我只是有一个关于如何获取包含十六进制数字的文件长度的快速问题.例如:
724627916C
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一方法是将十六进制值转换为二进制:
724627916C => 0111001001000110001001111001000101101100
Run Code Online (Sandbox Code Playgroud)
然后计算二进制值的位数.只是想知道这是否正确?谢谢
我正在使用Windows MFC应用程序.我正在准备我的设计中的报告列表,我CListCtrl可以列出文件的名称,大小,类型和修改日期.我不知道如何显示文件的大小.有谁知道怎么做?
当我运行我的程序并且我选择查看产品列表时,它不会打印任何内容.过了一段时间,我发现它的值fl_size总是为0.这是为什么?
void view_prdct_code_list() {
FILE *stock = fopen("stock.dat","r+");
assert(stock);
int fl_size=ftell(stock);
int prd_size= sizeof(product);
int quantity= fl_size/prd_size;
printf("fl_size=%d",fl_size);
fseek(stock,0,SEEK_SET);
prdct cprd= (product *)malloc (sizeof(product)*quantity);
assert(cprd);
int i;
fread(cprd,prd_size,quantity,stock);
for (i=0;i<quantity;i++){
printf("PRODUCT CODE: %d\n",cprd->code);
}
free(cprd);
fclose(stock);
}
Run Code Online (Sandbox Code Playgroud) 我目前正在编写一个简单的小型一次性垫程序.我希望它在keyfile小于source文件时警告用户,但是当我运行它时我的程序只是忽略它.
/* Check if keyfile is the same size as, or bigger than the sourcefile */
if(sizeof keyfile < sizeof sourcefile)
{
printf("Source file is larger than keyfile.\n");
printf("This significantly reduces cryptographic strength.\n");
printf("Do you wish to continue? (Y/N)\n");
scanf("%c", &ans);
if(ans == 'n' || ans == 'N')
{
return (1);
}
if(ans == 'y' || ans == 'Y')
{
printf("Proceeding with Encryption/Decryption.\n");
}
Run Code Online (Sandbox Code Playgroud)
我怀疑问题在于我的使用sizeof,但我不知道其他任何选择?有关如何更改我的代码以使其工作的任何建议?
编辑:我已尽力增加fstat我的能力,但它仍然以同样的方式作出反应......这就是我所做的:
/* Get size of sourcefile. */ …Run Code Online (Sandbox Code Playgroud)