2017-12-09 2 views
-1

csv 파일에서 historical s 및 p 500 주식 데이터 (1999-2013)를 가져 와서 내용을 화면에 인쇄하는 프로그램을 작성하려고합니다. csv 파일의 형식은 [yyyymmdd, 0, openprice, closeprice, low, high, volume]입니다. 예를 들어 데이터 a [19991123,0,42.2029,45.5656,39.0001,50.2143, 6753909]는 1999 년 11 월 23 일에 주식 a가 42.2029의 개시 가격을 가지고 45.5656의 종가를 가짐을 의미합니다. 내 프로그램은 내 while 루프에서 정보를 가져오고 데이터가 0으로 표시되고 가격이 2로 표시되는 지점까지 수행 할 수 있습니다. Mag는 모든 것이 기반으로하는 문자 배열입니다. ypg와 chr은 줄 단위로 csv 데이터를 가져옵니다. 그러면 ypg와 chr이 각각의 라인을 수정합니다. 출발 가격과 날짜는 각각 남았습니다. Here is a link to a webpage that will give you a zip file containing the CSV's of all the stocks I am using. Just click Free Data and then click Download.CSV 파일에서 데이터를로드하는 중 오류가 발생했습니다.

바라건대 나는 바보 같은 것을 정말로 풀 수 있습니다. 어떤 도움이라도 대단히 감사합니다.

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

//This gives us the length of the string for the file name which is vary 
//useful 
//for calling the file and assigning it memory. 
int mystrlen(const char *(*s)) 
{ 
int i =0; 
while (*s++) i++; 
return i; 
} 


//This is where the linked list is basically being created. 
void LOAD(FILE *(*Stream), FILE *(*stream), const char *stock) 
{ 

//Opening and rewinding file. 
int strlength = mystrlen(&stock); 
char src[37+strlength]; 
strcpy(src,"./quantquote_daily_sp500_83986/daily/"); 
strcat(src,stock); 
*stream = fopen(src, "r"); 
*Stream = fopen(src,"r"); 
rewind(*stream); 

if(*stream == NULL) 
{ 
printf("Error, invalid stock name. restarting program\n"); 
main(); 
} 

//while loop to print off the data to the screen. 
printf("Entering the while loop\n"); 
while(1) 
{ 
if((feof(*stream))) 
{ 
break; 
} 
char * Mag[55] = { NULL }; 

char * chr = (char *)malloc(sizeof(Mag)); 
char * ypg = (char *)malloc(sizeof(Mag)); 

fgets(chr, sizeof(Mag), *stream); 
fgets(ypg, sizeof(Mag), *Stream); 

char DATE[9]; 
char OPENPRICE[6]; 

//these create the variables necessary for the datalist. 
char * date = (char *)malloc(sizeof(chr)); 
date = chr; 

char * price = (char *)malloc(sizeof(ypg)); 
price = ypg; 

strtok(date,",0,"); 

price = strtok(NULL,","); 
price = strtok(NULL,","); 
strcpy(DATE,date); 
strcpy(OPENPRICE,price); 
int DAte = NULL; 
DAte = atoi(DATE); 
double openprice = 0; 
openprice = atof(OPENPRICE); 

//these two methods are supposed to populate datalist to the screen but 
//I keep getting errors. 

int * Date = (int *)malloc(9); 
*Date = (int)DAte; 
printf("The value of Date is %d\n", *Date); 

double * OpenPrice = (double *)malloc(6); 
*OpenPrice = openprice; 
printf("The value of Opening Price is: %lf\n", *OpenPrice); 


free(Date); 
free(OpenPrice); 

free(chr); 
free(ypg); 
} 
fclose(*stream); 
return; 
} 

//main function for program. 
int main(int argc, char **argv) 
{ 
printf("Welcome to Stock Simulator.\n"); 

char stock[50]; 
FILE *stream; 
FILE *Stream; 
int size; 
char src[50], dest[50]; 
char *namen = (char *)malloc(sizeof(char)); 

printf("\n"); 
printf("What is the name of the stock that you would like to analyze 
(Enter the stock ticker below):\n"); 
scanf("%s",stock); 

strcpy(dest, "table_"); 
strcat(dest, stock); 

printf("%s",dest); 
printf("\n"); 

strcpy(src, ".csv"); 
strcat(dest, src); 
printf("%s",dest); 
printf("\n"); 

LOAD(&Stream, &stream, dest); 

return 0; 
} 

나는 내 파일의 끝에 도달 할 때까지이 유사하고 반복 결과를 얻을 것으로 기대합니다. 내가 똑바로 프로그램을 실행

The value of Date is 19991118         
The value of Opening Price is: 42.207600 

. 나의 최종 결과는 이것 인 것을 끝낸다. 예외적으로 첫 번째 네 줄은 내 리눅스 터미널의 한계까지 뻗어있다.

The value of Date is 2.       
The value of Opening Price is: 0.000000.     
The value of Date is 2.      
The value of Opening Price is: 0.000000. 

Program received signal SIGSEGV, Segmentation fault. 
__strcpy_sse2_unaligned() at ../sysdeps/x86_64/multiarch/strcpy-   sse2-unaligned.S:296            
296 ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S: No such file or directory. 

Here is a screenshot reference.

이 내가 (숫자가 잘 시작하지만 엉망이되는 방법을 주목하라) 부하 및 라인 83에서 중단 점 설정과 디버깅 세션을 수행 할 때 발생하는 것입니다 :

The value of Date is 19991126       
The value of Opening Price is: 37.921900 




Breakpoint 2, LOAD (Stream=0x7fffffffdf30, stream=0x7fffffffdf28,   stock=0x7fffffffdfc0 "table_a.csv") at extracredit.c:83      
83  free(OpenPrice);        
(gdb) continue       
Continuing.          
The value of Date is 19991129       
The value of Opening Price is: 38.033200 



Breakpoint 2, LOAD (Stream=0x7fffffffdf30, stream=0x7fffffffdf28,   stock=0x7fffffffdfc0 "table_a.csv") at extracredit.c:83    
83  free(OpenPrice);             
(gdb) continue                
Continuing.                
The value of Date is 1999113           
The value of Opening Price is: 38.960900         

Breakpoint 2, LOAD (Stream=0x7fffffffdf30, stream=0x7fffffffdf28,   stock=0x7fffffffdfc0 "table_a.csv") at extracredit.c:83     
83  free(OpenPrice);              
(gdb) continue               
Continuing.             
The value of Date is 199912.           
The value of Opening Price is: 0.000000. 

Here is another screenshot for sake of reference.

+2

이 매우 광범위하다 불필요한 코드의 톤을 포함하고 실제 문을 포함하지 않는합니다 (예 : 디버거 출력 - 이미지 링크가 텍스트만큼 좋지 않음). 여기에서 [질문] 질문을 읽어보십시오. –

+0

이것은 내가이 사이트에서 물어 본 첫 번째 질문입니다. 이렇게되어 미안합니다. – Jack

+0

괜찮습니다. 이 사이트는 귀하가 사용할 수있는 대부분의 사이트와 조금 다릅니다. 오류 메시지와 디버거 출력을 포함시키고 관련 코드 만 게시하도록하여이 코드를 좋은 질문으로 만들 수 있습니다. –

답변

1

문제는 당신의 LOAD에() wher 당신이 원하는 경우 두 번째 진실에 대한 런타임 메모리 할당 사용의 malloc()

int strlength = mystrlen(&stock); 
char src[37+strlength]; 

잘못입니다 크기를주는 하나 개의 변수를 가지고 전자. 올바른 방법은 다음과 같습니다 : 문자열의 포인터 포인터가 대신 역 참조 캐릭터 라인의 포인터 때문에

char *src; 
src = malloc (37 + strlength) 
0

귀하의 mystrlen 기능이 작동하지 않습니다.

int mystrlen(const char *(*s)) 
{ 
    int i =0; 
    while (*s++) i++; // s contains address of pointer to string, 
        // s doesn't point to characters 
    return i; 
} 

역 참조 문자 전에 문자열에 대한 포인터를 역 참조, 함수의 새로운 버전,

int mystrlen(const char *(*s)) 
{ 
    int i =0; 
    const char* ptrToString = *s; 
    while (*ptrToString++) i++; 
    return i; 
} 
관련 문제