[C/C++]_[初级]_[把一个图片的数据存入到std::string里,使用_wfopen生成二进制文件]

场景:读取大数据文件的时候,可以以一个固定大小的buff分多次读取文件,每读取一个buff,就把它存入到一个std::string中,并写入到新的文件中。直到读完文件,同时关闭文件。

<pre name="code" class="cpp">// test_write_file.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <wchar.h>
#include <io.h>

using namespace std;

void testWriteImageDataToBinaryFile()
{
	std::string str;
	FILE* wfile;
	wfile =_wfopen(L"E:\\15.txt",L"wb");
	//从文件中读数据
	FILE *rfile =_wfopen(L"E:\\IMG_2314.JPG",L"rb");
	fseek(rfile,0,SEEK_END);
	unsigned int size =ftell(rfile);
	unsigned int buff[1024];
	unsigned int count =size/1024;
	unsigned int temp_size =count%1024;
	for(unsigned int i = 0;i<count;++i)
	{
		fread(buff,1024,1,rfile);
		//存到一个std::string里
		//写人数据到文件中
		str.append((const char*)buff,1024);
		fwrite(str.data(),str.size(),1,wfile);
		str.clear();
	}
	if(temp_size>0)
	{
	//写人数据到文件中
		fread(buff,temp_size,1,rfile);
		str.append((const char*)buff,temp_size);	                
                fwrite(str.data(),str.size(),1,wfile);
		str.clear();
	}
	fclose(rfile);
	fclose(wfile);
}


int _tmain(int argc, _TCHAR* argv[])
{
	testWriteImageDataToBinaryFile();
	return 0;
}

 

                
好的,我可以为您编写一个C语言程序,实现您的需求。以下是代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> int main() { // 源文件路径 wchar_t src_path[] = L"E:\\CSV\\"; // 目标文件路径 wchar_t dest_path[] = L"E:\\import\\"; // 列出源文件夹中的所有CSV文件 wchar_t cmd[100] = L"dir /b "; wcscat(cmd, src_path); wcscat(cmd, L"*.csv > files.txt"); system(cmd); // 读取文件列表 FILE* fp = fopen("files.txt", "r"); char line[256]; while (fgets(line, sizeof(line), fp)) { size_t len = strlen(line); if (len > 0 && line[len - 1] == '\n') { line[len - 1] = '\0'; } // 打开源文件 wchar_t src_file[100]; mbstowcs(src_file, line, strlen(line) + 1); wcscat(src_file, L".csv"); FILE* src_fp = _wfopen(src_file, L"rb"); if (!src_fp) { printf("Failed to open file %s\n", line); continue; } // 创建目标文件 wchar_t dest_file[100]; mbstowcs(dest_file, line, strlen(line) + 1); wcscat(dest_file, L".txt"); wcscat(dest_file, L".csv"); wcscat(dest_file, L".unicode"); wchar_t dest_full_path[200]; wcscpy(dest_full_path, dest_path); wcscat(dest_full_path, dest_file); FILE* dest_fp = _wfopen(dest_full_path, L"wb"); if (!dest_fp) { printf("Failed to create file %s\n", dest_file); fclose(src_fp); continue; } // 换编码并写入目标文件 wchar_t buf[1024]; while (fgetws(buf, sizeof(buf), src_fp)) { fprintf(dest_fp, "%ls", buf); } // 关闭文件 fclose(src_fp); fclose(dest_fp); } // 删除文件列表 fclose(fp); remove("files.txt"); return 0; } ``` 这个程序会列出指定路径中所有的CSV文件,并将它们换为Unicode编码后保存到指定路径中。您只需要将程序保存为一个名为 `convert.c` 的文件使用 C 编译器编译后运行即可。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值