C语言读写txt文件

1.从txt文件中按指定格式 读出:

int read_raw_hex_data(const char* path,int data_length ,int* a) {
	FILE* fpRead = NULL;
	int ret = 0;
	int i = 0;
	fopen_s(&fpRead, path, "r");
	if (fpRead == NULL)
	{
		printf("Fail to read raw data file!");
		ret = -1;
		return ret;
	}

	for (i = 0; i < data_length; i++)
	{
		fscanf_s(fpRead, "%x", &a[i]);
	}
	fclose(fpRead);

	return ret;
}

 2. 按指定格式保存到txt文件中:

int  save_data(const char* path, int data_length, double* a) {
	FILE* fpWrite = NULL;
	int i = 0;
	fopen_s(&fpWrite, path, "w");
	if (fpWrite == NULL)
	{
		printf("Failed to save data!");
		exit(1);
	}
	for (i = 0; i < data_length; i++)
		fprintf(fpWrite, "%.8f\n", a[i]);
	fclose(fpWrite);
	return 0;
}

3. 获取txt文件行数

//summarize the data count of a file
int data_count_sum(const char* file_name) {
	FILE* fp;
	int num = 1;
	char tmp;

	fopen_s(&fp, file_name, "r");
	if (fp == NULL)	{
		printf("Fail to get a correct data sum number!");
		exit(1);
	}
	
	while (!feof(fp)) {
		tmp = fgetc(fp);
		if (tmp == '\n')
			num++;
	}
	//fgetc(fp) && num++;
	printf("%s: %d charaters in the file\n", file_name, num);

	fclose(fp);
	return num;
}

4. 字符串切割

C++实现字符串切割

// String Split
vector<string> split(const string &str, const string &pattern)
{
	//const char* convert to char*
	char * strc = new char[strlen(str.c_str()) + 1];
	strcpy(strc, str.c_str());
	vector<string> resultVec;
	char* tmpStr = strtok(strc, pattern.c_str());
	while (tmpStr != NULL)
	{
		resultVec.push_back(std::string(tmpStr));
		tmpStr = strtok(NULL, pattern.c_str());
	}
	delete[] strc;
	return resultVec;
};

5. 按行读取txt文件,通过字符串切割定位目标并保存到新文件。

// Read txt by line
int read_txt_lines(const char* path, const char* dst_path)
{
	ifstream ifs(path);    
	ofstream ofs(dst_path); 
	string line;
	int rows = 0;
	while (getline(ifs, line)) 
	{
		vector<string>str_vector;
		str_vector = split(line, ",");
		if (!str_vector.empty()) {
			ofs << str_vector[0] << '\n';
			rows++;
		}
	}
	ifs.close();
	ofs.close();
	return rows;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东城青年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值