What is the problem with my code?
#include
#include
int main() {
FILE *file;
char string[32] = \"Teste de solução\";
I think Oli Charlesworth has given you the answer you need.
Here are some tips for you:
If you use a backslash inside a string, you must put two backslashes.
You should check the result of fopen()
, and if it is NULL
you should stop with an error.
You should not specify the size of the array for your string; let the compiler count how many characters to allocate.
In the for
loop, you should not hard-code the size of the string; use sizeof()
and let the compiler check the length, or else loop until you see the terminating nul byte. I suggest the latter.
Rewritten version:
#include
#include
int main() {
FILE *file;
int i;
char string[] = "Teste de solução";
file = fopen("C:\\tmp\\file.txt", "w");
if (!file) {
printf("error!\n");
}
printf("Digite um texto para gravar no arquivo: ");
for(i = 0; string[i] != '\0'; i++) {
putc(string[i], file);
}
fclose(file);
return 0;
}