我正在尝试将字符串(文本文件行)传递到数组(array
forf1
和array2
for f2
)中。当我只打印 时buffer
buffer2
,线条就很好了。当我尝试使用strcpy
程序通过它们时,没有明显的原因会崩溃。我尝试了以下方法:
- 使用二维数组无济于事
- 使用方法并尝试返回 char 然后将其传递给数组,所以我可以避免这种草率的代码,但现在就可以了。
我正在使用带有 DEV-C++ 的 Windows 7 x64。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *arrayF1[20] ;
char *arrayF2[20] ;
int i = 0;
int size = 1024, pos;
int c;
int lineCount = 0;
char *buffer = (char *)malloc(size);
char *buffer2 = (char *)malloc(size);
char *array[100];
char *array2[100];
if (argc!=3)
{
printf("\nCommand Usage %s filename.txt filename.txt\n", argv[0]);
}
else
{
FILE *f1 = fopen(argv[1], "r");
FILE *f2 = fopen(argv[2], "r");
if(f1)
{
do { // read all lines in file
pos = 0;
do{ // read one line
c = fgetc(f1);
if(c != EOF) buffer[pos++] = (char)c;
if(pos >= size - 1) { // increase buffer length - leave room for 0
size *=2;
buffer = (char*)realloc(buffer, size);
}
}while(c != EOF && c != '\n');
lineCount++;
buffer[pos] = 0;
// line is now in buffer
strcpy(array[i], buffer);
printf("%s", array[i]);
//printf("%s", buffer);
i++;
} while(c != EOF);
printf("\n");
fclose(f1);
}
printf("%d\n",lineCount);
free(buffer);
lineCount=0;
i=0;
if (f2)
{
do { // read all lines in file
pos = 0;
do{ // read one line
c = fgetc(f2);
if(c != EOF) buffer2[pos++] = (char)c;
if(pos >= size - 1) { // increase buffer length - leave room for 0
size *=2;
buffer2 = (char*)realloc(buffer, size);
}
}while(c != EOF && c != '\n');
lineCount++;
buffer2[pos] = 0;
// line is now in buffer
strcpy(array2[i], buffer);
//printf("%s", buffer2);
printf("%s", array2[i]);
i++;
} while(c != EOF);
printf("\n");
fclose(f2);
}
printf("%d\n",lineCount);
free(buffer2);
}//end first else
return 0;
}