What is the problem with my code?
#include
#include
int main() {
FILE *file;
char string[32] = \"Teste de solução\";
Evidently you are compiling this as C, not C++. VS doesn't support C99, in which case you may not do this:
for (int i = 0; i < 32; i++)
You need to do this instead:
int i;
...
for(i = 0; i < 32; i++)
Where the declaration of i
must come before all statements in the function.
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<stdio.h>
#include<string.h>
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;
}