| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Weird error with C streams
Hello,
I've read the chapter about C streams today and so I wrote a code to test it. It compiles well.. but when I run it, Windows shows a message that the program must be closed. The code: Code:
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char *str;
/* I already have tried:
str = "C Programming...\nLearning C Programming\n";
AND
str = (char*)malloc(180 * sizeof(char));
str = "C Programming...\nLearning C Programming\n";
And now this:*/
strcpy(str, "C Programming...\nLearning C Programming\n");
// But the error persists
if(!(fp = fopen("strings.txt", "w+")))
{
puts("Error while opening the file");
getchar();
return 0;
}
fputs(str, fp);
rewind(fp);
while(!feof(fp))
{
fgets(str, 80, fp);
printf("%s", str);
}
return 0;
}
Please, can you compile this code and see if it generates error to you too? Thanks, Alfred |
|
#2
|
|||
|
|||
|
I'm not near a compiler to find out whats causing the actual error but can tell you that the method for setting what str equals is the final method you tried -
Code:
str = (char*)malloc(180 * sizeof(char)); strcpy(str, "C Programming...\nLearning C Programming\n"); If you haven't got the first of these 2 lines then the program will crash since strcpy does *NOT* allocate memory itself. Hope this helps, -KM- |
|
#3
|
|||
|
|||
|
Thanks kode_monkey for your reply, I have found a solution:
Now all the things are clear. I was testing the code on DevC++. So, now I tested it on VS .NET, it had compiled and the error was generated, hence I started debugging. The file "fgets.c" that contains the source code for the function fgets has been opened. What it really does is change the string char by char by this code: if ((*pointer++ = (_TSCHAR)ch) == _T('\n')) The same as: char name[10] = "C Programming"; /* Changing */ name[0] = 'A'; name[1] = 'L'; Ok, no problem until here. char* str = "C Programming"; is a pointer to a CONST string. We can change to where this pointer point to, but we can't change this string. And was this I was trying to change. The function fegts was trying this: str[0] = 'B'; str[1] = 'A'; ... If fgets would do: str = "New string" it would work, because it would only changing where str points to. Cya. |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Weird error with C streams |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|