Linux文件I/O实验报告

10 篇文章 3 订阅
8 篇文章 9 订阅

实验代码下载地址:
https://download.csdn.net/download/Qingyuyuehua/16305028

任务1

在当前用户目录下创建数据文件student.txt,文件的内部信息存储格式为Sname:S#:Sdept:Sage:Ssex,即“姓名:学号:学院:年龄:性别”,每行一条记录,输入不少于10条学生记录,其中包括学生本人记录。编写程序task41.c,从文件中查找Sdept字段值为“计算机与网络安全学院”的文本行,输出到文件csStudent.txt中,保存时各字段顺序调整为S#:Sname:Sage: Ssex:Sdept。提示:从终端读入一个文本行到字符串 char buf[MAXSIZE]可调用函数可调用函数:“fgets(buf, MAXSIZE, stdin);”,其中stdin是表示键盘输入设备的文件指针。

代码:

#include<stdio.h>
#include<string.h>

#define SEARCH_EDU "计算机与网络安全学院" //待查学院
#define SIZE 10 //学生人数
#define FILE_NAME "./student.txt" //打开文件名
#define FILE_OUT "./csStudent.txt" //输出文件名
#define MAXSIZE 1024

typedef struct STUDENT
{
    char name[20];//姓名
    char sno[20];//学号
    char edu[50];//学院
    char age[4];//年龄
    char sex[4];//性别
}Student;

int main()
{
    Student students[SIZE];
    FILE* stuFile = fopen(FILE_NAME,"r"); 
    FILE* outFILE = fopen(FILE_OUT,"w");
    int i,j;
    char buf[MAXSIZE];
    //读取文件学生信息到内存
    for(int i = 0; i < SIZE; i++)
    {
        j = 0;
        fgets(buf,MAXSIZE,stuFile);
        sscanf(buf, "%[^:]:%[^:]:%[^:]:%[^:]:%[^\n]\n", students[i].name,
        students[i].sno,students[i].edu,students[i].age,students[i].sex);
    }
    //打印内存中所有学生数据到屏幕,检验错误
    for(int i = 0; i < SIZE; i++)
    {
        printf("%s %s %s %s %s\n", students[i].name,
        students[i].sno,students[i].edu,students[i].age,students[i].sex);
    }
    //输出指定学院的学生到文件
    for(int i = 0; i < SIZE; i++)
    {
        if(strcmp(students[i].edu,SEARCH_EDU) == 0)
        {
            fprintf(outFILE,"%s:%s:%s:%s:%s\n", students[i].sno,
            students[i].name,students[i].age,students[i].sex,students[i].edu);
        }
    }
}

在这里插入图片描述
在这里插入图片描述

任务2

调用Unix I/O库函数,编写程序task42.c,从键盘读入5个学生的成绩信息,包括学号、姓名、语文、数学、英语,成绩允许有一位小数,存入一个结构体数组,结构体定义为:
typedef struct _subject {
char sno[20];   //学号
char name[20];  //姓名
float chinese;   //语文成绩
float math;      //数学成绩
float english;   //英语成绩
} subject;
将学生信息,逐条记录写入数据文件data,最后读回第1、3、5条学生成绩记录,显示出来,检查读出结果是否正确。
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<fcntl.h>

#define SIZE 5

typedef struct _subject
{
    char sno[20];
    char name[20];
    float chinese;
    float math;
    float english;
}subject;

int main()
{
    subject subs[SIZE]; 
    printf("请输入五位学生的信息:\n");
    int j;
    for(j = 0; j < SIZE; j++)
    {
        scanf("%s",subs[j].sno);
        scanf("%s",subs[j].name);
        scanf("%f",&subs[j].chinese);
        scanf("%f",&subs[j].math);
        scanf("%f",&subs[j].english);
    }

    int fd,i;
    fd = open("data",O_WRONLY|O_CREAT|O_TRUNC,0777);
    for(i=0; i<SIZE; i++)
        write(fd,(void*)&subs[i],sizeof(subject));
    close(fd);

    subject sub;
    fd = open("data",O_RDONLY,0);
    for(i = 0; i < SIZE; i++)
    {
        read(fd,(void*)&sub,sizeof(subject));
        if(i == 0 || i == 2 || i == 4)
            printf("%s  %s  %f  %f  %f\n",sub.sno,sub.name,sub.chinese,
            sub.math,sub.english);
    }
    close(fd);
}

在这里插入图片描述

任务3

在Linux环境下,可以调用库函数gettimeofday测量一个代码段的执行时间,请写一个程序task43.c,测量read、write、fread、fwrite函数调用所需的执行时间,并与prof/gprof工具测的结果进行对比,看是否基本一致。并对四个函数的运行时间进行对比分析。提示:由于一次函数调用时间太短,测量误差太多,应测量上述函数多次(如10000次)运行的时间,结果才会准确。
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>
#include<sys/time.h>

int main()
{
    int fd1;//文件标识符
    FILE *fp;//文件指针
    char buf;//缓冲区
    struct timeval time_start;//开始测试时间
    struct timeval time_end;//结束测试时间
    //测试输入:read系
    fd1 = open("test.txt",O_RDONLY);
    fp = fopen("file.txt", "r");
    //测试read()
    gettimeofday(&time_start,NULL);
    read(fd1,&buf,1);
    gettimeofday(&time_end,NULL);
    double wa= time_end.tv_usec - time_start.tv_usec;
    double sa= time_end.tv_sec - time_start.tv_sec;
    double ms = wa / 1000.0 + sa * 1000.0;
    printf("read() %lfms\n",ms);
    //测试fread()
    gettimeofday(&time_start,NULL);
    fread(&buf, 1, 1, fp);
    gettimeofday(&time_end,NULL);
    wa= time_end.tv_usec - time_start.tv_usec;
    sa= time_end.tv_sec - time_start.tv_sec;
    ms = wa / 1000.0 + sa * 1000.0;
    printf("fread() %lfms\n",ms);
    close(fd1);
    fclose(fp);
    //测试输出:write系
    fd1 = open("test.txt",O_WRONLY,0777);
    fp = fopen("file.txt", "w");
    //测试write()
    gettimeofday(&time_start,NULL);
    write(fd1,&buf,1);
    gettimeofday(&time_end,NULL);
    wa= time_end.tv_usec - time_start.tv_usec;
    sa= time_end.tv_sec - time_start.tv_sec;
    ms = wa / 1000.0 + sa * 1000.0;
    printf("write() %lfms\n",ms);
    //测试fwrite()
     gettimeofday(&time_start,NULL);
    fwrite(&buf, 1, 1, fp);
    gettimeofday(&time_end,NULL);
    wa= time_end.tv_usec - time_start.tv_usec;
    sa= time_end.tv_sec - time_start.tv_sec;
    ms = wa / 1000.0 + sa * 1000.0;
    printf("fwrite() %lfms\n",ms);
    close(fd1);
    fclose(fp);
}

在这里插入图片描述

任务4

在Linux系统环境下,编写程序task44.c,对一篇英文文章文件的英文单词词频进行统计。
(1) 以“单词:次数”格式输出所有单词的词频(必做)
(2) 以“单词:次数”格式、按词典序输出各单词的词频(选做)
(3) 以“单词:次数”格式输出出现频度最高的10个单词的词频
例如,若某个输入文件内容为:
GNU is an operating system that is free software—that is, it respects users’ freedom. The development of GNU made it possible to use a computer without software that would trample your freedom.
则输出应该是:
GNU:2
is:3
it:2
……
提示:可以调用字符串处理函数、二叉树处理函数等库函数

思路:

1、读取字符串,文件按中以空格为分隔符读取,并判断读取的单词是否是单个单词,若不是,再拆分。

2、将已经提取的字符串储存在字符串数组中。

3、构建字典树,将字符串数组中的字符串加入到字典树

4、遍历字典树,将字符串和对于在文章中出现次数存储到二元组数组中,默认为字典序

5、使用自定义比较和交换,对二元组数组进行排序,输出前十个单词,如果不足十个,则输出全部单词。

6、清理所有malloc分配的内存。

代码:

C语言版本:

//FileInput.h
#ifndef FILEINPUT_H
#define FILEINPUT_H
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

//将文件指针里的单词输出到字符串数组,并返回单词数量
int ReadFromFile(char** s, FILE* fp);
#endif
//FileInput.c
#include"FileInput.h"

//将文件指针里的单词输出到字符串数组,并返回单词数量
int ReadFromFile(char** s, FILE* fp)
{
	char temp[1024];//缓冲区1
	char temp2[1024];//缓冲区2
	int i,j = 0;
	while (!feof(fp))
	{
		fscanf(fp, "%s", temp);
		for (i = 0; i < strlen(temp); i++)
		{
			if (tolower(temp[i]) < 'a' || tolower(temp[i]) > 'z')
			{
				temp[i] = ' ';
			}
		}
		int n = 0;
		while (n < strlen(temp) && sscanf(&temp[0] + n, "%s", temp2))
		{
			*(s + j) = (char*)malloc(sizeof(char) * (strlen(temp2) + 1));
			strcpy(*(s + j), temp2);
			n += strlen(temp2) + 1;
			strcpy(temp2, "\0");
			j++;
		}
	}
	return j;
}
//trie.h
#ifndef TRIE_H
#define TRIE_H

#include<ctype.h>
#include<stdlib.h>
#include<string.h>

#define SIZE 26 //字符个数限定

/*字符处理函数*/
//字符编码转数字0-25 不区分大小写
int Turn(char n);
//数字0-25转字符编码小写
char Rturn(int n);
/*字符处理函数*/

/*pair二元组定义*/
#define TYPE1 char*
#define TYPE2 int

typedef struct _Pair //Stack
{
    TYPE1 first;
    TYPE2 second;
}Pair;
//Pair构造函数
Pair* Pair_init(TYPE1 f, TYPE2 s);
//Pair析构函数
void Pair_destructor(Pair* p);
//Pair比较函数
int Pair_compare(Pair* a, Pair* b);
//Pair交换函数
void Pair_swap(Pair** a, Pair** b);
/*pair二元组定义*/

/*字典树定义*/
//字典树结点
typedef struct _TrieNode //Trie树结点
{
    int root; //是否根节点
    int num; //以该单词结尾的单词数量
    char c; //该节点存储的字符
    struct _TrieNode* pre; //父节点
    struct _TrieNode* next[SIZE];//将26个西方字符作为指针数组
}TrieNode;

//初始化字典树结点
TrieNode* TrieNode_init(int r, char s, TrieNode* p);
//初始化字典树根结点
TrieNode* TrieNode_init_root();
//清理结点
void TrieNode_clear(TrieNode* tn);

//Trie树
typedef struct _Trie //Trie树
{
    TrieNode* root;
    int num;
}Trie;

//初始化字典树
Trie* Trie_init();
//字典树析构
void Trie_destructor(Trie* trie);
//增加单词
void Trie_append(Trie* trie, const char* s);
//遍历
Pair** Trie_traverse(Trie* trie, int* n);
/*字典树定义*/

/*栈定义*/
#define DEFAULT_CAPACITY 3
#define TYPE TrieNode*

typedef struct _LinkNode //Stack结点
{
    TYPE data;//数据指针
    struct _LinkNode* pre;//链接指针
}LinkNode;

typedef struct _Stack //Stack
{
    LinkNode* stack_base;//基指针
    LinkNode* stack_top;//栈顶指针
}Stack;

//初始化
Stack* Stack_init();
//析构
void Stack_destructor(Stack* s);
//压栈
void Stack_push(Stack* s, TYPE d);
//退栈
void Stack_pop(Stack* s);
//取栈顶元素
TYPE Stack_top(Stack* s);
//判断栈空
int Stack_empty(Stack* s);
/*栈定义*/

/*辅助函数*/
//降序排序
void WordSort(Pair** p, int ls, int rs);
/*辅助函数*/
#endif
//trie.c
#include "trie.h"

/*字符处理函数*/
//字符编码转数字0-25 不区分大小写
int Turn(char n) 
{
    return tolower(n) - 97;
}
//数字0-25转字符编码小写
char Rturn(int n)
{
    return (char)(n + 97);
}
/*字符处理函数*/

/*字典树结点函数*/
//初始化字典树结点
TrieNode* TrieNode_init(int r, char s, TrieNode* p)
{
    TrieNode* t = (TrieNode*)malloc(sizeof(TrieNode));
    t->root = r;
    t->c = s;
    t->num = 0;
    t->pre = p;
    for (int i = 0; i < SIZE; i++)
    {
        t->next[i] = NULL;
    }
    return t;
}
//初始化字典树根结点
TrieNode* TrieNode_init_root()
{
    return TrieNode_init(1, '\0', NULL);
}
//清理结点
void TrieNode_clear(TrieNode* tn)
{
    for (int i = 0; i < SIZE; i++)
    {
        if (tn->next[i] != NULL)
        {
            TrieNode_clear(tn->next[i]);
        }
    }
    free(tn);
}
/*字典树结点函数*/

/*字典树函数*/
//初始化字典树
Trie* Trie_init()
{
    Trie* tr = (Trie*)malloc(sizeof(Trie));
    tr->root = TrieNode_init_root();//建立根结点
    tr->num = 0;
    return tr;
}
//字典树析构
void Trie_destructor(Trie* trie)
{
    TrieNode_clear(trie->root);
}

//增加单词
void Trie_append(Trie* trie, const char* s)
{
    TrieNode* nowNode = trie->root;
    for (int i = 0; i < strlen(s); i++)
    {
        if (nowNode->next[Turn(s[i])] != NULL)
        {
            nowNode = nowNode->next[Turn(s[i])];
        }
        else
        {
            nowNode->next[Turn(s[i])] = TrieNode_init(0, tolower(s[i]), nowNode);
            nowNode = nowNode->next[Turn(s[i])];
        }
        if (i == strlen(s) - 1)
        {
            nowNode->num++;
            trie->num++;
        }
    }
}

//返回目标结点的单词
char* Trie_reWork(TrieNode* n)
{
    char buf[1024];
    char* result;
    int i = 0,j = 0, size = 0;
    while (!n->root)
    {
        buf[i] = n->c;
        i++;
        n = n->pre;
    }
    buf[i] = '\0';
    size = strlen(buf);
    result = (char*)malloc(sizeof(char) * (size + 1));
    for (j = 0; j < size; j++)
    {
        result[j] = buf[i - j - 1];
    }
    result[size] = '\0';
    return result;
}

//遍历
Pair** Trie_traverse(Trie* trie,int * n)
{
    Stack* NodeStack = Stack_init();
    Pair** results = (Pair**)malloc(sizeof(Pair*) * trie->num);
    TrieNode* nowNode = trie->root;
    Stack_push(NodeStack, nowNode);
    int i = 0;
    while (!Stack_empty(NodeStack))
    {
        nowNode = Stack_top(NodeStack);
        Stack_pop(NodeStack);
        if (!nowNode->root && nowNode->num != 0)
        {
            *(results+i) = Pair_init(Trie_reWork(nowNode), nowNode->num);
            i++;
        }
        for (int j = SIZE - 1; j >= 0; j--)
        {
            if (nowNode->next[j])
                Stack_push(NodeStack,nowNode->next[j]);
        }
    }
    *n = i;
    Stack_destructor(NodeStack);
    return results;
}

/*栈函数*/
//栈构造函数
Stack* Stack_init()
{
    Stack* stacks = (Stack*)malloc(sizeof(Stack));
    stacks->stack_base = (LinkNode*)malloc(sizeof(LinkNode));
    stacks->stack_base->pre = NULL;
    stacks->stack_top = stacks->stack_base;
    return stacks;
}

//栈析构函数
void Stack_destructor(Stack* s)
{
    LinkNode* Node = s->stack_top;
    s->stack_top = s->stack_top->pre;
    free(Node);
    while (s->stack_top != NULL)
    {
        Node = s->stack_top;
        s->stack_top = s->stack_top->pre;
        free(Node);
    }
}

//入栈
void Stack_push(Stack* s, TYPE d)
{
    LinkNode* Node = (LinkNode*)malloc(sizeof(LinkNode));
    Node->data = d;
    Node->pre = s->stack_top;
    s->stack_top = Node;
}

//出栈
void Stack_pop(Stack* s)
{
    LinkNode* Node = s->stack_top;
    s->stack_top = s->stack_top->pre;
    free(Node);
}

//取栈顶
TYPE Stack_top(Stack* s)
{
    return s->stack_top->data;
}

//判断栈空
int Stack_empty(Stack* s)
{
    if (s->stack_base == s->stack_top)
        return 1;
    return 0;
}
/*栈函数*/

/*pair二元组*/
//Pair构造函数
Pair* Pair_init(TYPE1 f, TYPE2 s)
{
    Pair* pairs = (Pair*)malloc(sizeof(Pair));
    pairs->first = f;
    pairs->second = s;
}

//Pair析构函数
void Pair_destructor(Pair* p)
{
    free(p);
}

//Pair比较函数
int Pair_compare(Pair* a, Pair* b)
{
    if (a->second < b->second)
        return 0;
    else if (a->second > b->second)
        return 1;
    else if (strcmp(a->first, b->first) < 0)
        return 1;
    else
        return 0;
}

//Pair交换函数
void Pair_swap(Pair** a, Pair** b)
{
    Pair* temp = *a;
    *a = *b;
    *b = temp;
}
/*pair二元组*/

/*辅助函数*/
//降序排序(使用快速排序算法)
void WordSort(Pair** prs, int ls, int rs)
{
    int i, j ,p;
    Pair* pr;
    if (ls < rs)
    {   
        i = ls - 1;
        for(j = ls; j < rs; ++j)
        {
            if (Pair_compare(*(prs + j), *(prs + rs)))
            {
                ++i;
                Pair_swap((prs + i), (prs + j));
            }
        }
        Pair_swap((prs + i + 1), (prs + rs));
        p = i + 1;

        WordSort(prs, ls, p - 1);
        WordSort(prs, p + 1, rs);
    }
}
/*辅助函数*/
//main.c
#include<stdio.h>
#include<stdlib.h>
#include"FileInput.h"
#include"trie.h"

#define WORDALLS 1024 //最大单词数

int main()
{
	//变量定义
	FILE* fp; //文件指针
	char** words; //字符串数组
	int i,n,alls; 
	Trie* trie; //字典树
	Pair** pairs; //二元组数组
	//打开文件
	fp = fopen("file.txt", "r");
	if (!fp)
	{
		printf("File Error\n");
		exit(-1);
	}
	//建立字符串数组及初始化
	words = (char**)malloc(sizeof(char*) * WORDALLS);
	for (i = 0; i < WORDALLS; i++)
	{
		*(words + i) = NULL;
	}
	//从文件获取单词
	alls = ReadFromFile(words, fp);
	//创建字典树
	trie = Trie_init();
	//添加单词到字典树
	for (i = 0; i < alls; i++)
	{
		Trie_append(trie, *(words + i));
	}
	//遍历字典树,获得统计信息(二元组Pair)
	pairs = Trie_traverse(trie,&n);
	//按字典顺序输出
	printf("按字典顺序输出如下:\n");
	for (i = 0; i < n; i++)
	{
		printf("%s: %d\n", (*(pairs+i))->first, (*(pairs + i))->second);
	}
	//按次序输出最高十个单词
	WordSort(pairs, 0, n - 1);
	printf("\n按次数顺序输出最高十个单词:\n");
	n = n > 10 ? 10 : n;
	for (i = 0; i < n; i++)
	{
		printf("%s: %d\n", (*(pairs + i))->first, (*(pairs + i))->second);
	}
	//内存释放
	fclose(fp);
	for (i = 0; i < WORDALLS; i++)
	{
		free(*(words + i));
	}
	Trie_destructor(trie);
	for (i = 0; i < n; i++)
	{
		Pair_destructor(*(pairs + i));
	}
	free(pairs);
	//内存释放结束

	getchar();
	return 0;
}

运行结果:

在这里插入图片描述

C++代码实现:

排序算法可以直接调用Algorithm库的函数,便不写了

#ifndef TRIE_H
#define TRIE_H
#include<string>
#include<cctype>
#include<stack>
#include<vector>
#include<utility>
#include<iostream>

namespace lx //名称空间泠雪lx
{
    inline int Turn(char n) //字符编码转数字0-25 不区分大小写
    {
        return tolower(n) - 97;
    }

    inline char Rturn(int n) //数字0-25转字符编码小写
    {
        return char(n + 97);
    }

    const int SIZE = 26; //字符个数限定

    struct TrieNode //Trie树结点
    {
        bool root; //是否根节点
        int num; //以该单词结尾的单词数量
        char c; //该节点存储的字符
        TrieNode* pre; //父节点
        TrieNode *next[SIZE];//将26个西方字符作为指针数组

        TrieNode(bool r = true,char s = '\0', TrieNode* p = nullptr) //构造函数,初始化
        {
            root = r;
            c = s;
            num = 0;
            pre = p;
            for(int i = 0; i < SIZE; i++)
            {
                next[i] = nullptr;
            }
        }
    };

    class Trie //Trie树类
    {
    private:
        TrieNode *root;
        std::string reWork(TrieNode* n);
    public:
        Trie();  //构造函数,初始化
        void append(const std::string &s);  //增加单词
        int search(const std::string &s); //检索单词个数,不存在为0,存在返回个数
        std::vector<std::pair<std::string, int>> traverse(); //遍历
        ~Trie(); //析构函数
        void test();
    };

    void clear(TrieNode* tn); //清理结点
}
#endif
#include "trie.h"

namespace lx
{
    std::string Trie::reWork(TrieNode* n)
    {
        std::string temp;
        while (!n->root)
        {
            temp.insert(temp.begin(), n->c);
            n = n->pre;
        }
        return temp;
    }

    Trie::Trie()
    {
        root = new TrieNode();//建立根结点
    }

    void Trie::append(const std::string &s)
    {
        TrieNode *nowNode = root; //当前结点
        for (int i = 0; i < s.size(); i++)
        {
            if (nowNode->next[Turn(s[i])] != nullptr)
            {
                nowNode = nowNode->next[Turn(s[i])];
            }
            else
            {
                nowNode->next[Turn(s[i])] = new TrieNode(false, tolower(s[i]), nowNode);
                nowNode = nowNode->next[Turn(s[i])];
            }
            if (i == s.size() - 1)
            {
                nowNode->num++;
            }
        }
    }

    int Trie::search(const std::string &s)
    {
        TrieNode *nowNode = root; //当前结点
        for (int i = 0; i < s.size(); i++)
        {
            if (nowNode->next[Turn(s[i])] != nullptr)
            {
                nowNode = nowNode->next[Turn(s[i])];
                if (i == s.size() - 1)
                {
                    return nowNode->num;//返回数量
                }
            }
            else
            {
                return 0;//没找到
            }
        }
    }

    std::vector<std::pair<std::string, int>> Trie::traverse()
    {
        std::stack<TrieNode*> NodeStack;
        std::vector<std::pair<std::string, int>> results;
        TrieNode* nowNode = root;
        NodeStack.push(nowNode);
        while (!NodeStack.empty())
        {
            nowNode = NodeStack.top();
            NodeStack.pop();
            if (!nowNode->root && nowNode->num != 0)
            {
                results.push_back(std::pair<std::string,int>(reWork(nowNode),nowNode->num));
            }
            for (auto i = SIZE - 1; i >= 0; i--)
            {
                if (nowNode->next[i])
                    NodeStack.push(nowNode->next[i]);
            }
        }
        return results;
    }

    Trie::~Trie()
    {
        clear(root);
    }

    void Trie::test()
    {
        TrieNode* now = root->next[Turn('h')]->next[Turn('e')]->next[Turn('l')]->next[Turn('l')]->next[Turn('o')];
        std::cout << reWork(now) << std::endl;
    }

    void clear(TrieNode* tn)
    {
        for (int i = 0; i < SIZE; i++)
        {
            if (tn->next[i] != nullptr)
            {
                clear(tn->next[i]);
            }
        }
        delete tn;
    }
}
#include<iostream>
#include<fstream>
#include<vector>
#include<sstream>
#include"trie.h"

using namespace std;

void ReadFromFile(vector<string>& v,ifstream& fs);

int main()
{
	ifstream fin;
	fin.open("file.txt", ios_base::in);
	vector<string> words;
	ReadFromFile(words, fin);

	lx::Trie wordTree;
	for (const auto & i : words)
	{
		wordTree.append(i);
	}

	cout << "以字典序输出:" << endl;

	std::vector<std::pair<std::string, int>> works(move(wordTree.traverse()));
	for (auto i : works)
	{
		cout << i.first << ": " << i.second << endl;
	}

	

	cin.get();
}

void ReadFromFile(vector<string>& v, ifstream& fs)
{
	string temp;
	string temp2;
	istringstream sin;
	while (!fs.eof())
	{
		fs >> temp;
		for (auto& i : temp)
		{
			if (tolower(i) < 'a' || tolower(i) > 'z')
			{
				i = ' ';
			}
		}
		sin.str(temp);
		while (sin >> temp2)
		{	
			v.push_back(temp2);
		}
		sin.clear();
	}
}

Java代码实现:

来自 卢LKim大佬 的Java代码实现:

public class Struct1 {
	int count = 0;
	String str ="";
	Struct1(String str){
		count++;
		this.str += str;
	}
	@Override
	public boolean equals(Object obj) {
		boolean result;
		if(this == obj)  //内存地址一样
			return true;
		else {
			if(obj instanceof Struct1) {
				Struct1 temp = (Struct1)obj;
				result=temp.str.equals(this.str);
				if(result) {
					temp.count += this.count;//如果商品相同,则数量相加
				}
				return result;
			}
			else
				return false;
		}
	}
	@Override
	public int hashCode() {
		
		return str.hashCode();
	}
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class Test1 {
	public static void main(String[] args) throws FileNotFoundException {
		Scanner scan;
		BufferedReader reader = new BufferedReader(new FileReader("data"));
		Set<Struct1> set = new HashSet<Struct1>();
		String line;
		String str;
		try {
			while((line = reader.readLine()) != null) {
				scan = new Scanner(line); //扫描读取的一行字符串
				scan.useDelimiter("[^\\d\\w]");
//				scan.useDelimiter("[ ,—'\n]");   //空格分割
				while(scan.hasNext()) {
					str = scan.next();
					Struct1 temp = new Struct1(str);
					set.add(temp);
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Iterator<Struct1> it = set.iterator();
		while(it.hasNext()) {
			Struct1 a = it.next();
			if(!a.str.equals(""))
			System.out.println(a.str+": " + a.count);
		}
	}
}
  • 9
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值