安全方式fopen_s 读取TXT文件数据, fprintf_s写入数据到TXT操作

本文通过C++代码示例介绍了如何从文件中读取二维坐标数据,并将三维坐标数据写入文件的过程。示例代码展示了使用fscanf_s和fprintf_s函数进行数据读写的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 直接看代码示例

// 读取操作

vector<Point3f> w3Point;

vector<Point2f> uvSL;
    float tempx=0.0, tempy=0.0;
    FILE *fp;
        
    errno_t err = fopen_s(&fp, "cvSideCenter.txt", "rt"); //读取文件数据
    cout << err << endl;
    while (!feof(fp))
    {
        fscanf_s(fp, "%f %f\n", &tempx,&tempy);
        //cout << tempx << "..." << tempy << endl;
        Point2f temp(tempx, tempy);
        uvSL.push_back(temp);
    }
    fclose(fp);

// 写入操作

    err = fopen_s(&fp, "worldCenter.txt", "w+"); //写入文件数据
    cout << err << endl;
    for (int i = 0;i < w3Point.size();i++)
    {
        fprintf_s(fp, "%.2f %.2f %.2f\n", w3Point.at(i).x, w3Point.at(i).y, w3Point.at(i).z);
    }
    fclose(fp);

 

以下是将wav文件转换为txt格式的C语言代码示例: ```c #include <stdio.h> int main() { FILE *fp_in, *fp_out; char input_file[100], output_file[100], buffer[4]; int data_size, sample_rate, num_channels, byte_rate, bits_per_sample, i, j, sample; // 输入wav文件名 printf("Enter the input wav file name: "); scanf("%s", input_file); // 打开wav文件 if (fopen_s(&fp_in, input_file, "rb") != 0) { printf("Error opening input file.\n"); return 1; } // 读取wav文件头信息 fseek(fp_in, 22, SEEK_SET); fread(&num_channels, sizeof(short), 1, fp_in); fseek(fp_in, 24, SEEK_SET); fread(&sample_rate, sizeof(int), 1, fp_in); fseek(fp_in, 34, SEEK_SET); fread(&bits_per_sample, sizeof(short), 1, fp_in); fseek(fp_in, 40, SEEK_SET); fread(&data_size, sizeof(int), 1, fp_in); // 计算每个样本的字节数 byte_rate = num_channels * sample_rate * bits_per_sample / 8; // 输入txt文件名 printf("Enter the output txt file name: "); scanf("%s", output_file); // 打开txt文件 if (fopen_s(&fp_out, output_file, "w") != 0) { printf("Error opening output file.\n"); return 1; } // 读取每个样本并写入txt文件 for (i = 0; i < data_size / byte_rate; i++) { for (j = 0; j < num_channels; j++) { fread(buffer, sizeof(char), bits_per_sample / 8, fp_in); sample = 0; for (int k = 0; k < bits_per_sample / 8; k++) { sample |= buffer[k] << (k * 8); } fprintf(fp_out, "%d ", sample); } fprintf(fp_out, "\n"); } // 关闭文件 fclose(fp_in); fclose(fp_out); printf("Wav file converted to txt successfully.\n"); return 0; } ``` 运行此程序后,用户将被要求输入输入wav文件名和输出txt文件名。程序将打开输入文件读取其头信息,然后计算每个样本的字节数。接下来,程序将打开输出文件读取每个样本,并将其写入输出文件。最后,程序将关闭文件并打印成功消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值