c语言文件问题,希望大神指点,非常感谢

#include

#include
#include
typedef struct news
{
char name[10];
int age[5];
struct news *next;
}N;
int main()
{
int i;
N head;
FILE *fp;

N  *p,*newp;
fp=fopen("D:\\1.txt","r");
if(fp==NULL)
{
    printf("打开文件错误");-

fclose(fp);

 } 
while(!feof(fp)) 
{
newp=(N *)malloc(sizeof(N));

fscanf(fp,"%s",&p->name);

    fscanf(fp,"%s%d",&newp->name,&newp->age); 
    printf("%s %d",newp->name,newp->age);
    newp->next=head.next;
    head.next=newp; 
} 
fclose(fp);
printf("信息导入完毕") ; 

}

无法读中的数出文件 图片说明

7个回答

图片说明
年龄还是乱码

楼主,你把代码粘贴到“插入代码区”中,这样方便阅读,这样看上去,格式太乱,无法阅读

楼主,你好,是读不出数据吗?

qq_38210632
qq_38210632 回复lixiaogang_theanswer: 是的
2 年多之前 回复

如果你的问题是不能读出完整问题件的话,你可以试试改一下fopen的第二个参数:加上'b'属性。
在windows系统上这是有区别的,如果不加b,读取到第一个'\0'就会终止了。b --按二进制文件读取。
fp=fopen("D:\1.txt","rb");

DESCRIPTION
The fopen() function opens the file whose name is the string pointed to by path and associates a stream with it.

   The argument mode points to a string beginning with one of the following sequences (possibly followed by additional characters, as described below):

   r      Open text file for reading.  The stream is positioned at the beginning of the file.

   r+     Open for reading and writing.  The stream is positioned at the beginning of the file.

   w      Truncate file to zero length or create text file for writing.  The stream is positioned at the beginning of the file.

   w+     Open for reading and writing.  The file is created if it does not exist, otherwise it is truncated.  The stream is positioned at the beginning of the file.

   a      Open for appending (writing at end of file).  The file is created if it does not exist.  The stream is positioned at the end of the file.

   a+     Open  for  reading  and  appending  (writing at end of file).  The file is created if it does not exist.  The initial file position for reading is at the beginning of the file, but output is
          always appended to the end of the file.

   The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two-character strings described above.  This is strictly  for  com‐
   patibility with C89 and has no effect; the 'b' is ignored on all POSIX conforming systems, including Linux.  (Other systems may treat text files and binary files differently, and adding the 'b' may
   be a good idea if you do I/O to a binary file and expect that your program may be ported to non-UNIX environments.)

希望对你有帮助

图片说明

谢谢你,但是读出来的与文件中的完全不一样。

看代码,你的P都没有分配内存,肯定BUG,看你的意思好像是从文件中读取一条记录并加到LIST中,感觉没用把fscanf这个方法明白,这个是读一行,
看你的代码,文件中就要写成这样?

周杰伦
周杰伦 20

谢谢你,但是那我应该怎么改代码呀?

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!