gpt4 book ai didi

c - 如何在不使用字符数组的情况下从文件中读取字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 08:11:00 24 4
gpt4 key购买 nike

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

#define ZERO (0)
#define ONE (1)
#define TEN (10)
#define TWENTY (20)
#define FOURTY_SEVEN (47)
#define FIFTY_SEVEN (57)

typedef struct PHONE
{
char szName[20] ;

char szPhone[20] ;

struct PHONE *pNext ;
};

struct PHONE *pFirst = NULL ; // To denote start of the linked list

struct PHONE *pPointer = NULL ; // To denote current end node in linked list

struct PHONE *pNew = NULL ; // To denote the new node

struct PHONE *pTemp = NULL ; // To store pointer temporarily

struct PHONE *pTempForDeallocation = NULL ; // To store pointer for deallocation

struct PHONE stPhone ;

FILE *fPointerForOpen ; // To Open the file

int FilePresentOrNot() ; // To Check the file is present or not

int MemoryAllocation() ; // To Allocate Memory to the Linked List

int main()
{
int iChoice = 0 ;

int iRepeat = 0 ;

int iLength = 0 ;

do
{
fPointerForOpen = fopen("phonebook.txt","r");

fflush(stdin);

system("cls");

if(NULL == fPointerForOpen)
{
FilePresentOrNot();
}

// stPhone.szName = (char *)malloc(100);

while(fscanf(fPointerForOpen,"%s",stPhone.szName)!= EOF)
{
fscanf(fPointerForOpen,"%s",stPhone.szPhone);

pNew = (struct PHONE *) malloc(sizeof(struct PHONE)) ;

strcpy( pNew -> szName , stPhone.szName ) ;

strcpy( pNew -> szPhone , stPhone.szPhone ) ;

pNew ->pNext = NULL ;

MemoryAllocation() ;
}
printf("\n\nDo you Want to continue then press 1 ? \t");

scanf("%d",&iRepeat);

fclose(fPointerForOpen);

pFirst = NULL ;

}while(ONE == iRepeat);
return 0 ;
}


int MemoryAllocation()
{
if(NULL == pFirst)
{
pFirst = pNew ;

pPointer = pNew ;

}
else
{
pPointer->pNext = pNew ;

pPointer = pNew ;

}
}

这是代码。这里我使用数组读取姓名和电话号码,我想将该数组替换为指针。当我更换时,我只能阅读四个字符。

谁能帮我做一下,请告诉我它是否正确?

最佳答案

用这个替换你的结构;

  typedef struct PHONE
{
char *szName ;
char *szPhone ;
struct PHONE *pNext ;
};

然后每次你使用一个新的PHONE实例,分配你想要的内存;

  aPhone.szName = (char *)malloc(sizeOfNameBuffers);

或者 pNew->szName = (char *)malloc(sizeOfNameBuffers);

关于c - 如何在不使用字符数组的情况下从文件中读取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39515733/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com