I'm using Visual C++ 6.0, and I have the code below.
char filename[1000], string[5]; FILE *fin; strcpy(filename, argv[3]); if ((fin = fopen(filename, "r")) != NULL) { fgets(string, 100, fin); string[strlen(string)-1] = NULL; printf("filename = %s\n", filename); printf("argv[3]= %s\n", argv[3]); printf("string = %s\n", string); } argv[3] is the full path and filename, e.g. C:\Users\Desktop\file.txt, and the content of the file is
1 2 3 So "1" should be stored in the "string" variable.
However, for about 1 out of 4 runs, I would get the output
filename = C:\Users\Desktop\file.tx argv[3] = C:\Users\Desktop\file.txt string = <very long garbage value> Why did
strcpy(filename, argv[3]); not copy the entire string, missing the last "t"? And why is fin not NULL in this case, since the file should not have existed?
I should also add that this code exists in a multi-thread program, but only 1 thread executes this code.
char []andFILEinstead ofstd::stringand streams?std::string, like most otherstdcontainers, expands automagically to contain all the data you put into it, saving you from having to track lengths and memory allocation manually.