I am receiving warning: ignoring return value of 'getcwd', declared with attribute warn_unused_result #define get_current_dirr when running this code:
#define get_current_dir getcwd
FILE *open_particle_data()
{
FILE *data_file;
char data_file_name[] = "particle_data.txt";
char buff[FILENAME_MAX];
get_current_dir(buff, FILENAME_MAX);
char *output_dir;
char str1[] = "/output_data/";
output_dir = malloc(strlen(buff) + strlen(str1) + strlen(data_file_name) + 1);
strcpy(output_dir, buff);
strcat(output_dir, str1);
strcat(output_dir, data_file_name);
data_file = fopen(output_dir,"w");
free(output_dir);
return data_file;
Any help would be appreciated. Thanks
Various functions in Glibc are annotated in a way that suggests to the compiler that it is suspicious for their return values to be ignored. When GCC observes during compilation that the return value of such a function indeed is ignored, it (by default) issues a warning about that. That is what you are seeing.
The C language allows you to ignore function return values, but doing so is often a mistake. In particular, many functions' return values contain information about function success or failure, and neglecting to account for the possibility of failure can lead to erroneous, possibly even destructive behavior. And that may not manifest until later, making such issues difficult to debug.
getcwd()in particular returns a null pointer when it fails, and in that case you cannot rely on it to have written a valid string into the specified buffer. A robust program would detect such a return value and handle it gracefully. For example, the program might emit a diagnostic message and terminate when it observesgetcwd()to fail.On the other hand, if you just want to silence the error without actually fixing the issue, then you can cast the return value to
voidto explicitly indicate to GCC and to some other compilers that you are intentionally ignoring it. I do not recommend this.