我需要读取一个包含我的名字的 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/