Why can't I close the file - c

I have a problem when I close the file fc.
Here is my code
#include <stdio.h>
#include <wchar.h>
int main()
{
FILE* fc = fopen("template.txt","rt,ccs=UTF-8");
wchar_t subStr[2300];
fread(subStr,sizeof(wchar_t),2300,fc);
wchar_t* scrStr=new wchar_t[2300];
wcscpy(scrStr,subStr);
fclose(fc);
return 0;
}

The file was probably not opened correctly in the first place. You must check that the 'handle' to the stream returned by fopen is not NULL. The following code checks the file 'handle', with a few bits changed to make it 'reasonable' C.
#include <stdio.h>
#include <wchar.h>
int main()
{
wchar_t* scrStr = NULL;
FILE* fc = fopen("template.txt","rt,ccs=UNICODE");
// Check that the file was opened.
if(NULL != fc)
{
wchar_t subStr[2301];
size_t wcharsRead = fread(subStr, sizeof wchar_t , 2300, fc);
fclose(fc);
// Check if anything was read.
if(0 != wcharsRead)
{
// Terminate the string in the temporary buffer.
subStr[wcharsRead] = `\0`;
// Allocate a smaller string (use new, if you're in C++).
if(scrStr = malloc(1 + sizeof wchar_t * wcharsRead), NULL != scrStr)
{
// Copy the useful bit into the new string.
wcscpy(scrStr, subStr);
}
}
}
else
{
// Do some error handling
printf("Unable to open file. Error code: %d\r\n",errno);
}
// Check if a string was read.
if(NULL != scrStr)
{
// Do something with scrStr
// Free the string once it's finished with (use delete if you're in C++).
free(scrStr);
}
return 0;
}

Related

Listing files in a directory into array in C using strcpy and strncpy

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int main()
{
struct dirent *de;
char *filesList[258];
DIR *dr = opendir("C:\\Users\\Asus\\Desktop\\Training-Process-of-YOLO-architecture\\annotations");
if (dr == NULL)
{
printf("could not open folder");
return 0;
}
int i = 0;
while ((de = readdir(dr)) != NULL)
{
if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
{
}
else
{
filesList[i] = (char *)malloc(strlen(de->d_name) + 1);
strcpy(filesList[i], de->d_name); // strncpy add some unnecessary values at the end of some array elements
i++;
}
}
closedir(dr);
for (int i = 0; i < 256; i++)
{
printf("%s\n", filesList[i]);
}
return 0;
}
strncpy adds some junk values at the end of some array elements as follows.
2077.xml\ProgramΦ_U═≥
2080.xml$G
2083.xmlam FilesΦ_U═≥
2086.xmlll\ModulΦ_U═≥
2089.xmlstem32\WΦ_U═≥
2095.xml\v1.0\MoΦ_U═≥
2098.xml\ProgramΦ_U═≥
Here I'm reading xml files and adding them to an array. Above you can see some junk values are coming at the end of the elements. This doesn't happen with strcpy(). Can someone explain this behaviour ?
The posted code needs to pay attention to the fields:
/* Length of name without \0 */ size_t d_namlen;
/* File type */ int d_type;
Notice there is a 'name length' field that can be used when copying the directory name.
Notice the file type that can be used to determine if the current file is a 'normal' file or something else.

Passing file content into memory is faulty

I am wondering why while I think I make the function call to load appropriately,
it seems that fread cannot read into my chunk of memory correctly and so it creates a segmentation fault[in load function]!Please point me to the right approach
The link to the code is
#include <math.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
bool load(FILE* file, char** content, size_t* length);
int main()
{
// opens file
FILE * file = fopen("test.txt", "r");
// initialises variables
char* content;
size_t length;
// sending arguments to load function
bool receive = load(file, &content, &length);
// debugging content
printf("values of content: %s\n", content);
// debugs length
printf("values of content: %zu\n", length);
// closes file
fclose(file);
// for success
return 0;
}
bool load(FILE* file, char** content, size_t* length)
{
{
// proof checking for the existence of file
if (file == NULL)
{
return false;
}
// perusing to end of file
fseek(file, 0, SEEK_END);
// for approximation of size of file
size_t len = ftell(file);
// returns cursor to beginning of file
fseek(file, 0, SEEK_SET);
// apportions memory on heap for content of file
* content = (char *) malloc (len + 1);
// memory error checking
if(*content == NULL)
{
printf("It's unfortunate\n");
}
// to read into content
fread(* content, sizeof(char), len, file);
// null terminates content
(* content)[len] = 0;
// debugs content
printf(" content contains %s\n", * content);
// debugs length
* length = len;
printf(" length is %d\n", * length);
// if success
return true;
}
// if fail
return false;
}
Thank you
you need to check that the file opened OK
FILE * file = fopen("test.txt", "r");
if(file == NULL)
{
perror("failed to open file: ");
exit(1);
}
Secondly your load function returns false of it fails, but you dont check it. Do
bool receive = load(file, &content, &length);
if(!receive)
{
fprintf(stderr, "failed to read file");
exit(1);
}
in load you do
if(*content == NULL)
{
printf("It's unfortunate\n");
}
but carry on any way. You should do
if(*content == NULL)
{
printf("It's unfortunate\n");
return false;
}
In general you are not checking the return of any function you call, fseek,ftell,fread,.... You should not be surprised when your program fails. Yes its a boring slog, but thats just the way it is in C land

Reading a file, modifiying each line, storing it into a buffer, printing all at once

This is the file:
line 1
line 2
line 3
How to read the file line by line...
Append a suffix to each line..
FILE *fp = fopen ("file", "r");
while (fgets (buffer, sizeof (buffer), fp) != NULL) {
// append "test" to each line.
// store the result in a buffer named "result"
}
fclose (fp);
print the result all at once:
printf( "%s", result );
Expected result :
line 1test
line 2test
line 3test
The below program might do the requirement but it is not efficient enough. I am just giving a rough example. Hope this helps.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void display(char** temp,int LinesWritten);
int main()
{
FILE *fp;
char *buffer = (char*)malloc(sizeof(char)*101); // 101 is just an assumption. dynamic size may be decided
char **result = (char**)malloc(sizeof(char*)*10); // 10 is just an assumption. dynamic size may be decided
int LinesWritten = 0;
char **temp = result;
char **freetemp = result;
if((fp = fopen("file.txt","r"))==NULL)
{
printf("Error while opening file\n");
exit(1);
}
while((fgets(buffer,100,fp))&&(!(feof(fp)))) //assuming that 100 characters will be read into the buffer
{
if(*result = (char*)malloc(sizeof(char)*10))
{
sprintf(*result,"%s%s",buffer,"test");
*result++;
LinesWritten++;
}
}
fclose(fp);
display(temp,LinesWritten);
if(freetemp!=NULL)
{
free(freetemp);
}
return 0;
}
void display(char** temp,int LinesWritten)
{
for(int i=0;i<LinesWritten;i++)
{
printf("%s\n",*temp);
*temp++;
}
return;
}

Using fgets to read through file in C

I am trying to read through the file given then tokenize it. The only problem im having is fgets.The file open recieves no errors. I have seen this elsewhere on the site however no matter how i set this up including setting fileLine to a set amount like (char fileline [200]) i get a segmentation fault. Thanks in advance for any help.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[]){
char *fileName = "0";
char *tokenize, *savePtr;
struct Record *database= malloc(sizeof(database[0]));
int recordNum =0;
char *fileLine = malloc(sizeof(char *));//have replaced with fileline[200] still didnt work
FILE *fd = open(fileName,O_RDWR);
if(fd< 0){
perror("ERROR OPENING FILE");
}
while(fgets(fileLine,200,fd) !=NULL){
printf("%s\n", fileLine);
tokenize = strtok_r(fileLine,",",&savePtr);
while(tokenize != NULL){
//TOKENIZING into a struct
}
}
Why use open() with FILE? Use fopen() instead.
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char *fileName = "test.txt";
char *tokenize, *savePtr;
char fileLine[200] = {0}; // init this to be NULL terminated
FILE *fd = fopen(fileName, "r");
if (fd == 0) { // error check, equal to 0 as iharob said, not less than 0
perror("ERROR OPENING FILE");
return -1;
}
while (fgets(fileLine, 200, fd) != NULL) {
printf("%s\n", fileLine);
tokenize = strtok_r(fileLine, ",", &savePtr);
while (tokenize != NULL) {
tokenize = strtok_r(NULL, ",", &savePtr); // do not forget to pass NULL
//TOKENIZING into a struct
}
}
return 0;
}
As Weather Vane said, fd < 0 would work if you used open(). However, with fopen(), you should check to see if the pointer is NULL, ecquivalently fd == 0.
A comparison between this functions that open a file can be found in:
open and fopen function
C fopen vs open
The way I have it in mind is that fopen() is of higher level.
This line
char *fileLine = malloc(sizeof(char *));
allocates memory for a char * type, 4 or 8 bytes (depending on the platform).
So when you do
fgets(fileLine,200,fd)
it expects there to be 200 bytes of memory available.
Try this:
char *fileLine = malloc(200);
if (fileLine == NULL) { ... } // check for error
which will allocate the memory required.
You are using open() instead of fopen().
You can't be sure that the file did open correctly because fopen() does not return an integer, but a pointer to a FILE * object, on failure it returns NULL, so the right codition is
FILE *file;
file = fopen(filename, "r");
if (file == NULL)
{
perror("fopen()");
return -1;
}
In your code, you still go and use fgets() even when the fopen() fails, you should abort the program in that case.
Also, malloc() takes the number of bytes as the size parameter, so if you want fgets() to be limited to read just count bytes, then malloc() should be
char *buffer;
size_t count;
count = 200; /* or a value obtained someway */
buffer = malloc(count);
if (buffer == NULL)
{
fclose(file);
perror("malloc()");
return -1;
}
All the problems in your code would be pointed out by the compiler if you enable compilation warnings.

String search C program for command prompt

I wrote C program of searching string. The problem is MyStrstr() function doesn't work with
command prompt. It only works with IDE. So, can anyone advise me how to fix the code for working with command prompt. With regards...
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ARGUMENT_COUNT 3
#define FILE_INDEX 2
#define SEARCH_INDEX 1
#define BUFFER 256
#define SUCCESS 0
#define ERRCODE_PARAM 1
#define ERRCODE_FILENAME 2
#define MSG_USAGE "String Search Program === EXER5 === by Newbie\nUsage: %s Search_String fileName"
#define MSG_ERROR "Can not open file. [%s]"
char* MyStrstr(char* pszSearchString, char* pszSearchWord);
int main(int argc, char* argv[])
{
FILE* pFile = NULL;
char szData[BUFFER];
char* pszCutString = NULL;
if(argc != ARGUMENT_COUNT) {
printf(MSG_USAGE, argv[0]);
return ERRCODE_PARAM;
}
pFile = fopen(argv[FILE_INDEX], "r");
if(pFile == NULL) {
printf(MSG_ERROR, argv[FILE_INDEX]);
return ERRCODE_FILENAME;
}
pszCutString = MyStrstr(szData, argv[SEARCH_INDEX]);
if(pszCutString != NULL) {
printf("%s", pszCutString);
}
fclose(pFile);
pFile = NULL;
return SUCCESS;
}
char* MyStrstr(char* pszSearchString, char* pszSearchWord) {
int nFcount = 0;
int nScount = 0;
int nSearchLen = 0;
int nIndex = 0;
char* pszDelString = NULL;
char cSLen = 0;
size_t len = 0;
if(pszSearchString == NULL || pszSearchWord == NULL) {
return NULL;
}
while(pszSearchWord[nSearchLen] != '\0') {
nSearchLen++;
}
if(nSearchLen <= 0){
return pszSearchString;
}
cSLen = *pszSearchWord++;
if (!cSLen) {
return (char*) pszSearchString;
}
len = strlen(pszSearchWord);
do {
char cMLength;
do {
cMLength = *pszSearchString++;
if (!cMLength)
return (char *) 0;
} while (cMLength != cSLen);
} while (strncmp(pszSearchString, pszSearchWord, len) != 0);
return (char *) (pszSearchString - 1);
}
You want to open a file, search the contents of that file for a string and return/print that. You are instead doing:
char szData[256]; // <-- making an uninitialized buffer
char* pszCutString = NULL;
pFile = fopen(argv[2], "r"); // <-- Opening a file
pszCutString = MyStrstr(szData, argv[1]); // <-- searching the buffer
if(pszCutString != NULL) {
printf("%s", pszCutString);
}
fclose(pFile); // <-- Closing the file
So you never fill your buffer szData with the contents of the file noted in argv[2]. You're trying to search an uninitialized buffer for a string. You're luck the result is just "no output comes out".
You need to take the contents of the file in argv[2] and place it in the buffer szData then do the search. This could be accomplished by adding a call to a function like read() or fscanf()
Note 1:
I assume when you say this "worked" in the IDE, the code was a little different and you weren't using the command line arguments.
Note 2:
you should also check to fopen() worked before trying to read from/close pFile, and if your file is possibly larger than 256 characters you will need to change your code to either have a dynamically sized string, or you'll need to loop the buffer fills (but then you have to worry about breaking a word apart), or some other mechanism to check the full file.

Resources