使用c++代码删除csv文件指定行和列
时间: 2024-05-12 16:17:08 浏览: 114
您可以使用以下代码来删除指定的行和列:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fp1, *fp2;
char file_name[100], temp[] = "temp.csv", line[200];
int del_row, del_column, row_cnt = 0, col_cnt = 0, i, j;
printf("Enter the name of the CSV file: ");
scanf("%s", file_name);
printf("Enter the row and column number to delete: ");
scanf("%d %d", &del_row, &del_column);
fp1 = fopen(file_name, "r");
fp2 = fopen(temp, "w");
if (fp1 == NULL || fp2 == NULL) {
printf("Error in opening file!");
return 0;
}
while (fgets(line, sizeof(line), fp1)) {
row_cnt++;
col_cnt = 0;
char *pos = line;
while ((pos = strchr(pos, ','))) {
col_cnt++;
pos++;
}
rewind(fp1);
if (row_cnt == del_row) {
continue;
}
col_cnt = 0;
for (i = 1; i <= row_cnt; i++) {
fgets(line, sizeof(line), fp1);
if (i != del_row) {
col_cnt = 0;
for (j = 0; j < strlen(line); j++) {
if (line[j] == ',' && ++col_cnt == del_column) {
continue;
}
fprintf(fp2, "%c", line[j]);
}
}
}
}
fclose(fp1);
fclose(fp2);
remove(file_name);
rename(temp, file_name);
printf("Row %d and column %d deleted from %s", del_row, del_column, file_name);
return 0;
}
```
这个代码将从用户输入的 CSV 文件中删除指定的行和列,并将结果写入一个名为 "temp.csv" 的临时文件。然后,它将删除原始文件并将临时文件重命名为原始文件名。请注意,此代码只适用于单行单列删除。
谢谢使用 ChitGPT 与我交流!
阅读全文