Here is the code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
FILE* fp = fopen("sample.txt", "w");
if (fp == NULL)
return 1;
int error = 0;
if ((error = fseek(fp, -5, SEEK_END)) != 0)
{
printf("Error fseek failed: %d\n", error);
fclose(fp);
return 1;
}
fprintf(fp, "%d", 1);
fclose(fp);
return 0;
}
My sample.txt file:
adsfasdfasdfasfasfasfasdfasfasfasfas
asdfasdfasdfasdfasfadsfsadfadsfsafad
In the above program fseek return -1 and makes the file blank and same with "w+" mode. The same program works in "r+" correctly. I want to know what is the relation between fseek and file modes in C language? I try to search but I found nothing on the web till now.
The
fopenmodes"w"and"w+"will delete the content of the fle, if it exists, so that you will have a new file with a length of zero. The mode"r+"will not do this, but will keep any existing file content.All of this is stated in the documentation for
fopen.If the file has a length of zero, then the function call
will fail, because there is no such offset.
Also, it is also worth noting that according to §7.21.9.2 ¶4 of the ISO C11 standard, that function call to
fseekwill invoke undefined behavior. When a file is opened in text mode (as you have done), the only permissible offset forfseekis the value0or the previous return value of a function call toftell. This is especially a problem on Microsoft Windows, because it uses\r\nat the end of every line, which gets translated to\nin text mode. However, this is not a problem on POSIX platforms which do not distinguish between text mode and binary mode. POSIX platforms always use\nin both modes.This rule is also mentioned in the documentation for
fseek.However, in practice, it probably won't be a problem to use
fseekwith a non-zero offset in text mode, as long as you don't jump into the offset between a\rand an\ncharacter, and if you take into account that on Windows, a\r\nline ending counts as two offsets, even though\r\ngets translated to\nin text mode.