在C语言中,要从文件中删除某一数据,可以通过以下步骤实现:
打开要操作的文件,使用标准库中的fopen()函数来打开文件,指定打开方式为读写模式(“r+”)或者写入模式(“w”)。FILE *file = fopen("filename.txt", "r+");if (file == NULL) { printf("Error opening file.\n"); return 1;}读取文件中的数据,并将不需要删除的数据写入另一个临时文件中。可以使用fscanf()或fgets()函数来读取数据,并使用fprintf()函数将数据写入临时文件。FILE *temp = fopen("temp.txt", "w");if (temp == NULL) { printf("Error creating temp file.\n"); return 1;}int data;while (fscanf(file, "%d", &data) == 1) { if (data != data_to_delete) { fprintf(temp, "%d\n", data); }}关闭原文件和临时文件,并删除原文件。然后将临时文件重命名为原文件名。fclose(file);fclose(temp);remove("filename.txt");rename("temp.txt", "filename.txt");以上代码演示了如何从文件中删除特定数据,并将剩余数据写入新文件中。在实际使用中,可以根据具体需求和数据格式进行调整。




