65,210
社区成员
发帖
与我相关
我的任务
分享
#pragma warning (disable:4996)
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <stdlib.h>
#include <assert.h>
using namespace std;
#define LINE_LENGTH 1000
//获得文件行数和字节数
bool GetFileCountSize(const char *filepath, size_t &fcount, size_t &fsize)
{
FILE *fp = fopen(filepath, "r");
if (fp == NULL)
{
return false;
}
char buffer[LINE_LENGTH];
fcount = 0;
while (fgets(buffer, LINE_LENGTH, fp))
{
fcount++;
}
fsize = ftell(fp);
return true;
}
//比较大小,排序时用
int CompareLine(const void *pleft, const void *pritht)
{
return strcmp((*(char **)pleft), (*(char **)pritht));
}
int test_sort(char *in_filepath, char *out_filepath)
{
size_t fcount = 0, fsize = 0, cursize = 0;
GetFileCountSize(in_filepath, fcount, fsize);
//读取源文件内存并保存到内存中
FILE *fp = fopen(in_filepath, "r");
if (fp == NULL)
{
cerr << "can't open file " << in_filepath << endl;
return 1;
}
//预分配内存
char *FileStrings = new char[fsize + fcount];
char ** FileLines = new char *[fcount];
if (FileLines == NULL || FileLines == NULL)
{
cerr << "get memory error!" << endl;
}
FileLines[0] = FileStrings;
fgets(FileLines[0], LINE_LENGTH, fp);
for (size_t i = 1, j = 0; i < fcount; i++, j++)
{
FileLines[i] = FileLines[j] + strlen(FileLines[j]) + 1;
fgets(FileLines[i], LINE_LENGTH, fp);
}
//排序
qsort(FileLines, fcount, sizeof(FileLines[0]), CompareLine);
//sort(FileLines, FileLines + fcount, CompareLine);
fclose(fp);
//将排序结果写到目标文件
fp = fopen(out_filepath, "w");
if (fp == NULL)
{
cerr << "can't open file " << out_filepath << endl;
return 1;
}
for (size_t i = 0; i < fcount; i++)
{
fputs(FileLines[i], fp);
}
fclose(fp);
//释放内存
delete FileStrings;
delete FileLines;
return 0;
}
int main(int argc, char *argv[])
{
return test_sort(argv[1], argv[2]);
}
int main(int argc, char *argv[])
{
//char *strings[] = {"asf3223", "aesf534", "ase54", "3asef", "qe32", "adsgh", "asdaf34", "q23r34w", "saf", "2231e", "1231"};
size_t fcount = 0;
size_t fsize = 0;
char *FileStrings;
char ** strings;
//读源文件
if (!LoadFile(argv[2], fcount, fsize, FileStrings, strings)) return 1;
if (argv[1] == string("memcmp"))
{
for (int i = 0; i < fcount; i++)
{
for (int j = 0; j < fcount - i - 1; j++)
{
if (memcmp(strings[j], strings[j + 1], strlen(strings[j])) < 0)
{
char *tmp = strings[j];
strings[j] = strings[j + 1];
strings[j + 1] = tmp;
}
}
}
}
else
{
for (int i = 0; i < fcount; i++)
{
for (int j = 0; j < fcount - i - 1; j++)
{
if (strcmp(strings[j], strings[j + 1]) < 0)
{
char *tmp = strings[j];
strings[j] = strings[j + 1];
strings[j + 1] = tmp;
}
}
}
}
for (size_t i = 0; i < fcount; i++)
{
cout << strings[i] << endl;
}
return 0;
}
real 0m39.09s
user 0m22.17s
sys 0m2.80s
real 0m38.33s
user 0m22.74s
sys 0m5.84s