c - 读取然后重写和修改txt文件

标签 c string text

我需要读取一个包含我的名字的 txt 文件,然后创建一个包含我的名字的新 txt 文件,但将它倒过来拼写,即(John Doe 变成 Doe, John)。我的作业说我可能需要创建一个临时数组来存储更改的 txt。

我收到警告:内置函数“strchr”错误的隐式声明不兼容。我会将它包含到代码中,这样您就可以准确地看到我收到此警告的位置。

这是我的代码,我感觉好像很接近。我在这里做错了什么?请帮帮我。

#include <stdio.h>

int main (void)
{
FILE* txtFile=NULL;

txtFile=fopen("myName.txt", "r");

char myName [50]={'\0'};



if(txtFile==NULL)
{
    printf("Failed to open file\n");
}
else
{
    fgets(myName, sizeof(myName), txtFile);

    printf("%s\n", myName);
}

FILE* newTxtFile=NULL;

newTxtFile=fopen("myNewName.txt", "w+");

char newName[50]={'\0'};


if(newTxtFile==NULL)
{
    printf("Failed to open file\n");
}
else
{   
fgets(newName, sizeof(newName), newTxtFile);

fprintf(txtFile, "%s", newName);

rewind(newTxtFile);
//
char * space;
char *first=NULL;
char *last = NULL;
char *firstspace;
char *name=NULL;

name = myName;
//incompatible implicit declaration of built-in function 'strchr'
firstspace=space=strchr(name,' ');

*firstspace='\0';

while (space!=NULL)
{
    last = space+1;
    space=strchr(space+1,' ');
}

printf("%s %s", last, name);

*firstspace=' ';
//
printf("text: %s \n", newName);
}
fclose(txtFile);

return 0;
}   

最佳答案

您的代码中有很多无用的垃圾。

你的新文件没有任何内容的原因是你在以前的文件中再次写入新数据

看这里:

fprintf(txtFile, "%s", newName);



#include <stdio.h>
#include <string.h>

int main (void)
{
FILE* txtFile=NULL;

txtFile=fopen("helloWorld.txt", "r");

char myName [50]={'\0'};



if(txtFile==NULL)
{
    printf("Failed to open file\n");
}
else
{
    fgets(myName, sizeof(myName), txtFile);

    printf("%s\n", myName);
}

FILE* newTxtFile=NULL;

newTxtFile=fopen("myNewName.txt", "w+");

char newName[200]={'\0'};


if(newTxtFile==NULL)
{
    printf("Failed to open file\n");
}
else
{
fgets(newName, sizeof(newName), newTxtFile);


rewind(newTxtFile);
//
char * space;
char *first=NULL;
char *last = NULL;
char *firstspace;
char *name=NULL;

name = myName;
//incompatible implicit declaration of built-in function 'strchr'
firstspace=space=strchr(name,' ');

*firstspace='\0';

while (space!=NULL)
{
    last = space+1;
    space=strchr(space+1,' ');
}

printf("%s %s", last, name);
/* my changes start here*/
strcat(newName,last);


strcat(newName," ");


strcat(newName,name);

printf("%s", newName);

fprintf(newTxtFile, "%s", newName);






}
fclose(txtFile);
fclose(newTxtFile);

return 0;
}

关于c - 读取然后重写和修改txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19453127/

相关文章:

c - 将 9 位值的流作为字节写入 C 中的文件

c - 文件 I/O 中的缓冲区大小

javascript - 限制 Javascript 打印输出中的字符

c - const 在这种情况下做什么 - const int *ptr;

c - 我在以下代码中读取动态字符串时出错 :

c++ - 如何使用 std::map 将字符串和字符对映射到字符串?

string - 如何检查字符串是否包含 Kotlin 中的子字符串?

c# - 从字符串中提取所有出现的特定字符

swift - 如何设置UILabel中部分文本的位置

javascript - 我可以从文本或文本区域之外的文本选择中获取 Javascript 事件吗?