strcpy(home,"");
for(j=del1;j<del2;j++){
home[ strlen(home) ] = word[j];
printf("your house is %s",home);
但我得到了垃圾。我试着这样做:
strcat(word[j],home);
但是当我运行它时它不起作用
我正在尝试创建一个简单的程序来从文件中写入/读取单词:
TO WRITTE:
fp = fopen ( "houses.txt", "a" );
fprintf(fp,"%s&",home);
fclose ( fp );
printf(" Inserted element\n");
阅读:
char c, home[50],word[100];
strcpy(home,"");
int i=0,del1=0,del2=0,j;
FILE *fp;
fp = fopen ( "houses.txt", "r" );
while (c!=EOF)
{
c=getc(fp);
word[i]=c;
i=i+1;
if (c=='&')
{
del2=i-1;
strcpy(home,"");
for(j=del1;j<del2;j++)
{
strcat(word[i], home);// OR home[ strlen(home) ] = word[j];
}
del1=del2;
printf("%s \n",home);
}
}
fclose ( fp );
答案 0 :(得分:1)
如果您要做的只是打印文件中的每个&
分隔字符串,那么您应该只是将字符读入缓冲区,直到找到&
。然后,用&
替换\0
,打印缓冲区,然后将插入点重置为缓冲区的开头。这样的事情(注意没有任何错误检查)。
#include <stdio.h>
int main(int argc, char **argv)
{
char home[50];
int i, c;
FILE *fp;
fp = fopen ("houses.txt", "r");
i = 0;
while ((c = fgetc(fp)) != EOF) {
if (c == '&') {
home[i] = '\0';
puts(home);
i = 0;
}
else {
home[i++] = c;
}
}
fclose ( fp );
return 0;
}
或者,您可以使用fscanf
为您寻找&
:
#include <stdio.h>
int main(int argc, char **argv)
{
char home[50];
FILE *fp;
fp = fopen ("houses.txt", "r");
while (fscanf(fp, "%[^&]&", home) == 1) {
puts(home);
}
fclose ( fp );
return 0;
}