我有一個簡單的方法,需要一個文件名和一個指向鏈接列表的指針。鏈表似乎沒有任何問題。但是,我注意到由於某種原因,strcpy似乎無法覆蓋曾經存在的字符串。每次我覆蓋char數組時,副本會越來越糟糕。 爲什麼strcpy堅持以前的數據?爲什麼我的strcpy()不覆蓋整個字符串並保留最後一個字符[]的字符?
void readFile(struct record ** recordArray, char inputArray [])
{
struct record ** temp = recordArray;
char theString [100];
char characterInput;
int counter = 0;
counter = 0;
FILE * infile = fopen(inputArray, "r");
char name [100];
char address [100];
int yearofbirth;
char telno [20];
int target = 0;
/*
0 name
1 address
2 yearofbirth
3 telno
*/
/*If the file exists*/
if (infile != NULL)
{
while (characterInput != EOF)
{
characterInput = fgetc(infile);
if (characterInput == '\n')
{
theString[counter] = '\0';
if (target == 0)/*name*/
{
strcpy(name, theString);
counter = 0;
target++;
}
else if (target == 1) /*address*/
{
strcpy(address, theString);
counter = 0;
target++;
}
else if (target == 2) /*yearofbirth*/
{
yearofbirth = atoi(theString);
counter = 0;
target++;
}
else if (target == 3) /*telephone number*/
{
strcpy(telno, theString);
counter = 0;
target = 0;
addRecord(temp, name, address, yearofbirth, telno);
}
}
else /*if the character is not a null line ie its a regular character*/
{
theString[counter] = characterInput;
counter++;
}
}
}
else
{
printf("Error: There has to be a file named: %s\n", inputArray);
}
fclose(infile);
}
INPUT:
bill
firstaddress
9119398644
1993
tim
birch st.
7567115
1980
roger
wood st drive
4830382
1909
OUTPUT:
Name: bill
Address: firstaddress
Birthyear: 529464052
Telephone Number: 1993398644ss
Name: tim3398644ss
Address: birch st.4ss
Birthyear: 7567115
Telephone Number: 1980115t.4ss
Name: timmy15t.4ss
Address: wood st drive
Birthyear: 4830382
Telephone Number: 1909382 drive
編輯:
這是結束工作的代碼。謝謝你們。
void readFile(struct record ** recordArray, char inputArray [])
{
struct record ** temp = recordArray;
char theString [100];
char characterInput;
int counter = 0;
counter = 0;
FILE * infile = fopen(inputArray, "r");
char name [100];
char address [100];
int yearofbirth;
char telno [20];
int target = 0;
/*
0 name
1 address
2 yearofbirth
3 telno
*/
/*If the file exists*/
if (infile != NULL)
{
while (characterInput != EOF)
{
characterInput = fgetc(infile);
if (characterInput == '\n')
{
theString[counter] = '\0';
if (target == 0)/*name*/
{
strcpy(name, theString);
counter = 0;
target++;
}
else if (target == 1) /*address*/
{
strcpy(address, theString);
counter = 0;
target++;
}
else if (target == 2) /*yearofbirth*/
{
yearofbirth = atoi(theString);
counter = 0;
target++;
}
else if (target == 3) /*telephone number*/
{
strcpy(telno, theString);
counter = 0;
target = 0;
addRecord(temp, name, address, yearofbirth, telno);
}
}
else /*if the character is not a null line ie its a regular character*/
{
theString[counter] = characterInput;
counter++;
}
}
}
else
{
printf("Error: There has to be a file named: %s\n", inputArray);
}
fclose(infile);
}
時間來學習如何使用調試器。 – juanchopanza
(1)當你閱讀一個換行符時,你不會終止'theString'的空字符''\ 0''。 (2)當追加數據時,你不會防止'theString'溢出。 –
@juanchopanza,我認爲你是對的! – Tyler