cpp: read and write utf-8 text file using vs 2022

2023-11-10

/*****************************************************************//**
 * \file   geovindu.h
 * \brief  业务操作方法
 *
 * \author geovindu,Geovin Du
 * \date   2023-04-22
***********************************************************************/
/**
 * https://learn.microsoft.com/zh-cn/cpp/build/reference/utf-8-set-source-and-executable-character-sets-to-utf-8?view=msvc-170
 *
 * .
 */
 
 
#pragma once
 
#define _UNICODE
 
#ifndef GEOVINDU_H
#define GEOVINDU_H
 
#include <iostream>
#include <windows.h>
#include<string>
#include<string.h>
#include<fstream>
#include<stdio.h>
#include<cstdlib>
#include<cstring>
#include<iomanip>
#include <iostream>
#include <windows.h>
 
 
namespace geovindu
{
 
    class Geovin
    {
 
    private:
 
    public:
 
 
        /// <summary>
        ///
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        //string to_utf8(const wchar_t* buffer, int len);
        /// <summary>
        ///
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        //string to_utf8(const wstring& str);
 
        /// <summary>
        ///
        /// </summary>
        /// <param name="str"></param>
        //void createFile(wstring& str);
        /// <summary>
        /// 写成UTF-8文本文件
        /// </summary>
        void createFile();
 
    };
 
};
 
 
#endif
#define UNICODE

#define _UNICODE
 
#include <iostream>
#include <windows.h>
#include<string>
#include<string.h>
#include<fstream>
#include<stdio.h>
#include<cstdlib>
#include<cstring>
#include<iomanip>
#include "geovindu.h"
 
 
using namespace std;
 
namespace geovindu
{
 
    /// <summary>
    ///
    /// </summary>
    /// <param name="buffer"></param>
    /// <param name="len"></param>
    /// <returns></returns>
    string to_utf8(const wchar_t* buffer, int len)
    {
        int nChars = ::WideCharToMultiByte(
            CP_UTF8,
            0,
            buffer,
            len,
            NULL,
            0,
            NULL,
            NULL);
        if (nChars == 0) return "";
        string newbuffer;
        newbuffer.resize(nChars);
        ::WideCharToMultiByte(
            CP_UTF8,
            0,
            buffer,
            len,
            const_cast<char*>(newbuffer.c_str()),
            nChars,
            NULL,
            NULL);
 
        return newbuffer;
    }
    /// <summary>
    ///
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    string to_utf8(const wstring& str)
    {
        return to_utf8(str.c_str(), (int)str.size());
    }
    /// <summary>
    ///
    /// </summary>
    void createFile(wstring& strchinese)
    {
 
        ofstream testFile;
 
        testFile.open("demoinput.txt", std::ios::out | std::ios::binary);
 
        //std::wstring text = strchinese;          
 
        std::string outtext = to_utf8(strchinese);
 
        testFile << outtext;
 
        testFile.close();
 
    }
    ///<summary>
    /// 现有的文本写成UTF-8文本文件
    ///</summary>
    void Geovin::createFile()
    {
 
        ofstream testFile;
 
        testFile.open("geovindudemo.txt", std::ios::out | std::ios::binary);
 
        std::wstring text =
            L"涂聚文,你好,世界欢迎你!동생은 점수를 많이 땄어요\t geovindu\n Geovin Du \nНематериальное наследие водной рифмы\n"
            L"奇松・怪石・雲海と温泉\t大黄河を望む炳霊寺、驚異の張掖丹霞とシルクロードの要所9日間\n"
            L"Tours más solicitados\tParaíso en la Tierra - 13 Días\n"
            L"Entdecken Sie die schönsten Reiseziele von China mit unseren empfohlenen Touren.\n"
            L"Explorez les destinations les plus étonnantes de la Chine avec les visites recommandées.\n"
            L"\n";
 
        std::string outtext = to_utf8(text);
 
        testFile << outtext;
 
        testFile.close();
 
    }
 
};
 
#define UNICODE

// ConsoleTextFileDemoApp.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//geovindu Geovin Du
#define _UNICODE
#define _CRT_SECURE_NO_WARNINGS
 
 
#include <iostream>
#include <windows.h>
#include <string>
#include <string.h>
#include <fstream>
#include <stdio.h>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <cstdio>
#include <codecvt>
#include <assert.h>
#include <windows.h>
#include <iostream>
#include <fstream>
#include <io.h>
#include <vector>
 
#include "ConvertEncode.h"
#include "geovindu.h"
#include "FileHelper.h"
 
 
using namespace std;
using namespace geovindu;
 
 
 
 
 
/// <summary>
/// 写成UTF-8文本文件
/// </summary>
void createFile(wstring& strchinese)
{
    ConvertEncode encode;
    wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> convert;
 
    ofstream testFile;
 
    testFile.open("geovinduinput.txt", std::ios::out | std::ios::binary);
 
    //std::wstring text = strchinese;
 
 
    std::string outtext = convert.to_bytes(strchinese);//
 
    testFile << outtext;
 
    testFile.close();
 
    std::string narrowStr = convert.to_bytes(strchinese);
    {
        std::ofstream ofs("geovinduinput2.txt");            //文件是utf8编码
        ofs << narrowStr;
    }
 
}
/// <summary>
/// 读文写文件 utf-8的文本文件
/// </summary>
void readfile()
{
    ConvertEncode encode;
    char sname[50];
    string stuID;//学号
    int num;//编号
    double english;//英语成绩
    double math;//数学成绩
    double cpp;//C++成绩
    vector<string> lines;
    string line;
    ifstream fin;
    fin.open("geovinduinput.txt", ios::in); //utf-8文件读
    if (!fin)
    {
        cout << "Fail to open the file!" << endl;
        exit(0);
    }
 
    //创建链表,并保存数据
    while (1)
    {
        if (!(fin >> sname >> stuID >> english >> math >> cpp))//从文件中读取数据 中文没有读出来
        {
            break;
        }
        else
        {
            cout << encode.UTF8ToGBDu(sname) << "\t" << stuID << "\t" << english << "\t" << math << "\t" << cpp << endl;
        }
    }
 
    while (getline(fin, line)) {
        lines.push_back(line);
    }
    fin.close();
    //cout << encode.UTF8ToGBDu(sname) << "\t" << stuID << "\t" << english << "\t" << math << "\t" << cpp << endl;
     
}
 
 
const int FBLOCK_MAX_BYTES = 256;
/*
// File Type.
typedef enum FileType
{
    ANSI = 0,
    unicode,
    UTF8,
}FILETYPE;
 
FILETYPE GetTextFileType(const std::string& strFileName);
 
int UnicodeToANSI(char* pDes, const wchar_t* pSrc);
*/
 
int main(void)
{
    std::cout << "Hello World! 涂聚文\n";
 
     
 
 
 
 
    /*代码无用
            FileHelper helper;
            // file test.
            std::string strFileANSI = "studentANSI.txt";
            std::string strFileUNICODE = "student.txt";
            std::string strFileUTF8 = "geovindudemo.txt";
 
            // please change the file name to test.
            std::string strFileName = strFileUTF8;
            //文件类型没有读对
            TEXTFILETYPE fileType = helper.GetTextFileType(strFileName);
 
            if (TextFileType_UNICODE == fileType)
            {
                wchar_t szBuf[FBLOCK_MAX_BYTES];
                memset(szBuf, 0, sizeof(wchar_t) * FBLOCK_MAX_BYTES);
 
                std::string strMessage;
 
                FILE* fp = NULL;
                fp = fopen(strFileName.c_str(), "rb");
                if (fp != NULL)
                {
                    // Unicode file should offset wchar_t bits(2 byte) from start.
                    fseek(fp, sizeof(wchar_t), 0);
                    while (fread(szBuf, sizeof(wchar_t), FBLOCK_MAX_BYTES, fp) > 0)
                    {
                        char szTemp[FBLOCK_MAX_BYTES] = { 0 };
 
                        helper.UnicodeToANSI(szTemp, szBuf);
                        strMessage += szTemp;
                        memset(szBuf, 0, sizeof(wchar_t) * FBLOCK_MAX_BYTES);
                    }
                }
                cout << "UNICODE" << endl;
                std::cout << strMessage << std::endl;
 
                fclose(fp);
            }
            else if (TextFileType_UTF8 == fileType)
            {
                char szBuf[FBLOCK_MAX_BYTES];
                memset(szBuf, 0, sizeof(char) * FBLOCK_MAX_BYTES);
 
                std::string strMessage;
 
                FILE* fp = NULL;
                fp = fopen(strFileName.c_str(), "rb");
                if (fp != NULL)
                {
                    // UTF-8 file should offset 3 byte from start position.
                    fseek(fp, sizeof(char) * 3, 0);
                    while (fread(szBuf, sizeof(char), FBLOCK_MAX_BYTES, fp) > 0)
                    {
                        strMessage += szBuf;
                        memset(szBuf, 0, sizeof(char) * FBLOCK_MAX_BYTES);
                    }
                }
                cout << "utf-8" << endl;
                std::cout << strMessage << std::endl;
 
                fclose(fp);
            }
            else
            {
                char szBuf[FBLOCK_MAX_BYTES];
                memset(szBuf, 0, sizeof(char) * FBLOCK_MAX_BYTES);
 
                std::string strMessage;
 
                FILE* fp = NULL;
                fp = fopen(strFileName.c_str(), "rb");
                if (fp != NULL)
                {
                    // common file do not offset.
                    while (fread(szBuf, sizeof(char), FBLOCK_MAX_BYTES, fp) > 0)
                    {
                        strMessage += szBuf;
                        memset(szBuf, 0, sizeof(char) * FBLOCK_MAX_BYTES);
                    }
                }
                cout << "ANSI" << endl;
                std::cout << strMessage << std::endl;
 
                fclose(fp);
 
 
            }
 
 
    */
 
 
 
 
    readfile();
    //读内容
    //std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
    //std::ifstream ifs(L"geovinduinput.txt");
    //while (!ifs.eof())
    //{
    //  string line;
    //  getline(ifs, line);
    //  wstring wb = conv.from_bytes(line);
    //  wcout.imbue(locale("chs"));         //更改区域设置 只为控制台输出显示 其他语言显示不了,中文可以
    //  wcout << wb << endl;
    //}
    //ifs.close();
 
 
    Geovin geovin;
    geovin.createFile();
    wstring allstr;
    wstring sname;
    wstring stuID;//学号
    int num;//编号
    double english;//英语成绩
    double math;//数学成绩
    double cpp;//C++成绩
    int location = 0;//位置编号
    int flag = 0;//标记是否有对应的编号
 
    wcout << "请输入新增学生的信息" << endl;
    wcout << "姓名\t" << "学号\t" << "英语\t" << "数学\t" << "C++\t" << endl;
    wcin.imbue(locale("chs"));//获取的是中文
    
    wcin >> sname >> stuID >> english >> math >> cpp;
 
    //allstr = sname + ' ' + stuID;
    allstr.append(sname); //C++ wstring::append
    allstr.append(L"\t");
    allstr.append(stuID);
    allstr.append(L"\t");
    allstr.append(to_wstring(english));
    allstr.append(L"\t");
    allstr.append(to_wstring(math));
    allstr.append(L"\t");
    allstr.append(to_wstring(cpp));
   // createFile(allstr);
 
 
    system("pause");
    return 0;
 
 
}
 
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
 
// 入门使用技巧:
//   1. 使用解决方案资源管理器窗口添加/管理文件
//   2. 使用团队资源管理器窗口连接到源代码管理
//   3. 使用输出窗口查看生成输出和其他消息
//   4. 使用错误列表窗口查看错误
//   5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
//   6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
 
 
 
 
 
#define UNICODE

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

cpp: read and write utf-8 text file using vs 2022 的相关文章

随机推荐

  • CTFSHOW内部赛web5_登陆就有flag

    网站地址 https ctf show 经过一番固定的注入尝试发现 1 长度限制为5 2 存在过滤且过滤的字符会有回显 能留下来的字符很少这里列出 gt lt 在排除一下 gt lt 可以只留等于号 逗号和点号暂时没想出来怎么利用 所以可用
  • 手把手操作JS逆向爬虫入门(三)---Headers请求头参数加密

    知识点 1 请求头加密参数分析 2 JS base64加密的多个实现方法 目标网站 aHR0cHM6Ly93d3cub2tsaW5rLmNvbS96aC1jbi9idGMvdHgtbGlzdD9saW1pdD0yMCZwYWdlTnVtPT
  • STM32 ADC转换实验

    摘自 STM32 ADC转换实验 作者 追兮兮 发布时间 2020 10 29 09 42 24 网址 https blog csdn net weixin 44234294 article details 109333307 STM32
  • 通过scrapy命令行工具做网页分析

    前言 Scrapy是由python语言开发的一个快速 高效的web抓取框架 用于抓取web站点并从页面中提取结构化的数据 只需要实现少量的代码 就能够快速的抓取 它最吸引人的地方在于它是一个爬虫框架 任何人都可以根据自己的需求方便的修改 s
  • Windows 下Maven安装配置(本地仓库配置)

    一 下载maven maven官网 http maven apache org 下载下来也就是一个压缩文件 解压 我下载的是3 5 2版本 解压之后如下 路径为 D Program Files apache maven 3 5 2 二 配置
  • idea繁体字-中文输入法变繁体字

    今天提交代码发现 在IDEA中输入法突然变成繁体字 解决方案如下 idea中适用的快捷键和你输入法快捷键冲突 具体是crtl shift f
  • Docker学习

    目录 外部访问容器 映射所有接口地址 映射到指定地址的指定端口 映射到指定地址的任意端口 查看映射端口配置 容器互联 新建网络 连接容器 Docker Compose 配置 DNS 高级网络配置 快速配置指南 容器访问控制 容器之间访问 访
  • 解决iframe重定向让父级页面跳转

    原文 http www jb51 net article 40583 htm 有内嵌iframe的页面 当session过期时 点击连接重定向后的跳转会在iframe中跳转 在登录页面中加入下面的代码 就会在最外层页面跳转 原文 http
  • JVM 默认Xss大小

    abin lee java XX PrintFlagsFinal version grep ThreadStackSize intx CompilerThreadStackSize 0 pd product intx ThreadStack
  • 独步潮流!如何在私有数据集上塑造GPT式大型语言模型的独特风格!

    导读 Fine tune 是一种能够以成本效益的方式调整预训练 LLM 的技巧 本文主要比较了用于最新的开源 LLM Falcon 的不同参数高效微调方法 并为大家介绍如何使用单个 GPU 并在一天内对开源的大语言模型 Falcon 进行微
  • 【色度学】光度学基础

    1 光的本质 1 波长不同的可见光 引起人眼的颜色感觉不同 2 人们观察到的颜色是物体和特有色光相结合的结果 而不是物体产生颜色的结果 2 光度量 ISP 光的能量与颜色 1 mjiansun的博客 CSDN博客 ISP 光的能量与颜色 2
  • 鸿蒙2.0都来了,一起把环境搭建起来!

    自4月底开始 鸿蒙2 0系统便迎来公测 6月2日将举行鸿蒙操作系统以及华为全场景新品发布会 届时会正式推出鸿蒙OS稳定版 针对华为发布的鸿蒙系统 网上评论褒贬不一 有吹捧的 有无脑黑的 在这里一口君就不做评价了 但是有2点 对任何一个新兴事
  • spdk探秘-----vhost 、ISCSI、 NVMe-oF Target

    vhost target 这里我们主要介绍用SPDK vhost target来加速虚拟机中的I O 在介绍这个加速方案之前 我们先看看主流的I O设备虚拟化的方案 纯软件模拟 完全利用软件模拟出一些设备给虚拟机使用 主要的工作可以在Sim
  • http://www.xxx.com/ skipped. Content of size 67099 was truncated to 59363

    如果提示http www xxx com skipped Content of size 67099 was truncated to 59363 在nutch site xml中添加
  • python关系运算符连续使用_Python比较运算符(关系运算符)

    比较运算符 也称关系运算符 用于对常量 变量或表达式的结果进行大小比较 如果这种比较是成立的 则返回 True 真 反之则返回 False 假 True 和 False 都是 bool 类型 它们专门用来表示一件事情的真假 或者一个表达式是
  • Redis配置类

    天行健 君子以自强不息 地势坤 君子以厚德载物 每个人都有惰性 但不断学习是好好生活的根本 共勉 文章均为学习整理笔记 分享记录为主 如有错误请指正 共同学习进步 Redis配置类 Redis配置类1 Redis配置类2 在使用redis时
  • python 生成器

    生成器 对象后续元素按照某种算法推算出来 在python中 这种一边循环一边计算的机制 称为生成器 得到生成器的方法 1 利用列表推导式得到 cat generator py usr bin env python coding utf8 g
  • idea自动生成单元测类

    Navigate between tests and production code Intellj idea 中创建测试 test intellij idea 自动生成test单元测试 IntelliJ IDEA如何创建测试类 在Inll
  • 令人头秃的:你的主机中的软件中止了一个已建立的连接

    此文章来源于项目官方公众号 AirtestProject 版权声明 允许转载 但转载必须保留原链接 请勿用作商业或者非法用途 1 前言 最近在答疑群中 经常看到同学们遇到 你的主机中的软件中止了一个已建立的连接 这样的报错 这个报错可能的原
  • cpp: read and write utf-8 text file using vs 2022

    file geovindu h brief 业务操作方法 author geovindu Geovin Du date 2023 04 22 https learn microsoft com zh cn cpp build referen