我正在开发一个linux程序,它应该解析从另一台计算机或互联网下载的文件,并从该文件中收集信息。该程序还必须按例程重新下载文件,每n天/小时/分钟/其他,并再次解析它,以保持更新,以防文件已经改变。
然而,解析文件的过程可能需要大量的资源。因此,我想要一个函数来检查文件自上次下载以来是否发生了变化。我想象一下这样的例子:
int get_checksum(char *filename) {
// New prototype, if no such function already exists in standard C-libraries
int result; // Or char/float/whatever
// ...
return result;
}
int main(void) {
char filename[] = { "foo.dat" };
char file_url[] = { "http://example.com/foo.dat" }
int old_checksum; // Or char/float/whatever
int new_checksum; // Or char/float/whatever
// ...
// Now assume that old_checksum has a value from before:
dl_file(filename, file_url); // Some prototype for downloading the file
if ((new_checksum = get_checksum(filename)) == -1) {
// Badness
}
else {
if (new_checksum != old_checksum) {
old_checksum = new_checksum;
// Parse the file
}
else {
// Do nothing
}
}
// ...
}Q1:标准C/C++库中有像 get_checksum 这样的函数(从上面的例子中)吗?
Q2:如果不是:实现这一目的的最佳方法是什么?
不需要:
发布于 2014-04-15 22:49:41
您可以使用stat()函数。它允许您访问文件参数,如上次访问时间、上次修改的时间、、文件大小等:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};但是您需要对要使用它的文件具有执行权限。
手册页
发布于 2014-04-15 22:51:29
您可以执行XOR散列,其中只需对连续的无符号ints/longs块进行xor处理,但这会出现冲突问题。例如,如果文件主要是字符,那么大部分字节将位于正常的ASCII/Unicode字符的范围内,因此将有大量未使用的密钥空间。
对于标准实现,可以将文件读入字符串并使用C++11. http://en.cppreference.com/w/cpp/utility/hash中的std::散列。
以下是第一种方法的示例:
unsigned int hash(vector<char> file){
unsigned int result;
int *arr = (int*)file.data();
for(int i = 0;i < file.size() / sizeof(unsigned int);i++)
result ^= arr[i];
return result;
}你只需要把文件读入矢量。
发布于 2014-04-15 22:55:17
在C++语言中没有构建任何东西,直到std::hash<> in C++11,这是非常简单的,但可能适合您的需要。
上一次我检查了Boost (最常见的C++库扩展)中什么都没有。这里讨论了这一推理,但可能是过时的:
http://www.gamedev.net/topic/528553-why-doesnt-boost-have-a-cryptographic-hash-library/
所以,你最好的选择是:
带有文件内容的std::散列。
或者,下面这样的内容可能有用,可以保存到一个简单的标题中并链接:
http://www.zedwood.com/article/cpp-md5-function
或者您可以获得一个库,如OpenSSL或Crypto++。
https://stackoverflow.com/questions/23095897
复制相似问题