How I can edit a file while copying its content from another
source = fopen("sourceFile.txt", "r");
if( source == NULL )
{
printf("Error in doStepOneAndTwo, can't open file source \n");
return USERERR;
}
target = fopen("targetFile.txt", "w");
if( target == NULL )
{
fclose(source);
printf("Error in doStepOneAndTwo, can't open file target %s \n",str);
return USERERR;
}
while( ( ch = fgetc(source) ) != EOF )
{
fputc(ch, target);
//Here I need to check if ch == "blah" change it to "twoBlah" and save twoBlah to targetFile.txt instead of blah
}
I have problem with the syntax
const char *search_word = "blah";
const char *replace_word = "twoBlah";
const char *p = search_word;
while(1){
ch = fgetc(source);
if(*p == ch){
++p;
if(!*p){//match!
fprintf(target, "%s", replace_word);
p = search_word;
}
} else {
if(p != search_word){
const char *temp = search_word;
while(temp != p)
fputc(*temp++, target);
p = search_word;
}
if(ch == EOF)
break;
fputc(ch, target);
}
}
Related
Im trying to capture the data from the AT command response but im unable to do so.
My Approach.
functions():
#define MAX_LINE_LENGTH (8 * 1024)
static char buf[MAX_LINE_LENGTH];
static char buf2[MAX_LINE_LENGTH];
static bool tr_lf_cr(const char *s)
{
char *p;
p = strchr(s, '\n');
if (p == NULL || p[1] != '\0') {
return false;
}
*p = '\r';
return true;
}
static void strip_cr(char *s)
{
char *from, *to;
from = to = s;
while (*from != '\0') {
if (*from == '\r') {
from++;
continue;
}
*to++ = *from++;
}
*to = '\0';
}
#define STARTS_WITH(a, b) ( strncmp((a), (b), strlen(b)) == 0)
main()
fd = fopen(*mp, "r+b");
if (fd == NULL) {
/* Could not open the port. */
perror("open_port: Unable to open /dev/ttyUSB0\n");
}
char str = '\n';
strncat(cmd, &str, 1);
success = tr_lf_cr(cmd);
if (! success) {
fprintf(stderr, "invalid string: '%s'\n", cmd);
return EXIT_FAILURE;
}
int res = fputs(cmd, fd);
if (res < 0) {
fprintf(stderr, "failed to send '%s' to modem (res = %d)\n", cmd, res);
return EXIT_FAILURE;
}
do {
line = fgets(buf, (int)sizeof(buf), fd);
if (line == NULL) {
fprintf(stderr, "EOF from modem\n");
return EXIT_FAILURE;
}
strcpy(buf2, line);
strip_cr(buf2);
char delim[] = ",";
char *ptr = strtok(buf2, delim);
printf("\n0++++++++++++++++++++\n");
while (ptr != NULL) {
printf("'%s'\n", ptr);
ptr = strtok(NULL, delim);
}
printf("\n1********************\n");
} while (STARTS_WITH(line, "OK") == 0);
I get the following output when i run this command AT^HCSQ?
0++++++++++++++++++++
'AT^HCSQ?
'
0++++++++++++++++++++
'^HCSQ: "WCDMA"'
'64'
'64'
'60'
'0
'
0++++++++++++++++++++
'
'
0++++++++++++++++++++
'OK
'
What i want to achieve is to store each value separately from the buffer like
char p = WCDMA;
int rssi = atoi[ptr];
[etc...]
Im using strtok() to achieve this but im unable to skip the empty lines i get from the response. What should i do here?
This program should read rows and count operators, but counts wrong and can not find out where the errors are.
Help me find out the bugs and fix the program to be able to count rows and operators correctly.I've already tried several ways to fix it and it still counts wrong.
Current output:Broqt na operatorite e:1
Broqt na redovete e:1119
Expected output: Broqt na operatorite e:11
Broqt na redovete e:221
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
void cycleOperatorsCounter(FILE* inputStream, FILE* outputStream);
void counter(FILE* inputStream, FILE* outputStream);
int fileToFile(void);
int fileToScreen(void);
int screenToFile(void);
int screenToScreen(void);
void getFileName(char* fileName, int mode);
int menu() {
int i;
printf("----1. FILE TO FILE \n");
printf("----2. FILE TO SCREEN \n");
printf("----3. KBRD TO FILE \n");
printf("----4. KBRD TO SCREEN \n");
printf("----0. EXIT \n");
do {
printf("SELECT OPTION: ");
fflush(stdin);
scanf("%i", &i);
} while (i < 0 || i> 4);
return i;
}
int main(void) {
while (1) {
system("cls");
switch (menu()) {
case 1: fileToFile();
break;
case 2: fileToScreen();
break;
case 3: screenToFile();
break;
case 4: screenToScreen();
break;
default:
return 0;
}
system("pause");
}
}
void getFileName(char* fileName, int mode) {
while (1) {
fflush(stdin);
if (mode == 1) {
printf("Input file name(.C): ");
gets(fileName);
if (fileName[strlen(fileName) - 2] == '.' && toupper(fileName[strlen(fileName) - 1]) == 'C') {
return;
}
}
else {
printf("Output File: ");
gets(fileName);
return;
}
}
}
int fileToFile(void) {
char inputFileName[256], outputFileName[256];
FILE *inputStream, *outputStream;
getFileName(inputFileName, 1);
if (!(inputStream = fopen(inputFileName, "r"))) {
fprintf(stderr, "Error opening file!\n");
return -1;
}
getFileName(outputFileName, 2);
if (!(outputStream = fopen(outputFileName, "w"))) {
fprintf(stderr, "Error opening file!\a\n");
return -1;
}
cycleOperatorsCounter(inputStream, outputStream);
rewind(inputStream);
counter(inputStream, outputStream);
fclose(inputStream);
fclose(outputStream);
printf("Results saved to \"%s\".\n", outputFileName);
return 0;
}
int fileToScreen(void) {
char inputFileName[256];
FILE* inputStream;
getFileName(inputFileName, 1);
if (!(inputStream = fopen(inputFileName, "r"))) {
fprintf(stderr, "Error opening file!\n");
return -1;
}
cycleOperatorsCounter(inputStream, stdout);
rewind(inputStream);
counter(inputStream, stdout);
fclose(inputStream);
return 0;
}
int screenToFile(void) {
char outputFileName[256];
FILE *outputStream, *tempStream;
char str[999];
tempStream = fopen("temp.tmp", "w");
fflush(stdin);
printf("Napishete \"KRAI\" na nov red, kogato vuvedete teksta\n");
while (1) {
gets(str);
if (!strcmp(str, "KRAI")) {
fclose(tempStream);
tempStream = fopen("temp.tmp", "r");
break;
}
fprintf(tempStream, "%s\n", str);
}
getFileName(outputFileName, 2);
if (!(outputStream = fopen(outputFileName, "w"))) {
fprintf(stderr, "Error opening file!\a\n");
return -1;
}
cycleOperatorsCounter(tempStream, outputStream);
rewind(tempStream);
counter(tempStream, outputStream);
fclose(tempStream);
fclose(outputStream);
printf("Results saved to \"%s\".\n", outputFileName);
return 0;
}
int screenToScreen(void) {
FILE *tempStream;
char str[999];
tempStream = fopen("temp.tmp", "w");
fflush(stdin);
printf("Napishete \"KRAI\" na nov red, kogato vuvedete teksta\n");
while (1) {
gets(str);
if (!strcmp(str, "KRAI")) {
fclose(tempStream);
tempStream = fopen("temp.tmp", "r");
break;
}
fprintf(tempStream, "%s\n", str);
}
cycleOperatorsCounter(tempStream, stdout);
rewind(tempStream);
counter(tempStream, stdout);
fclose(tempStream);
return 0;
}
void cycleOperatorsCounter(FILE* inputStream, FILE* outputStream) {
char str[1000];
int cycleCounter = 0;
unsigned i;
while (fgets(str, sizeof(str), inputStream) != NULL) {
for (i = 0; i < strlen(str); i++) {
if ((str[i-1] == ' ' || str[i-1] == '\n' || str[i-1] == '\t' || i==0) &&
(str[i] == 'i') && (str[i + 1] == 'f') && (str[i+3] == ' ' || str[i+3] ==
'\n' || str[i+3] == '\t')) {
cycleCounter++;
}
if ((str[i-1] == ' ' || str[i-1] == '\n' || str[i-1] == '\t' ||
i==0)
&& (str[i] == 'e') && (str[i + 1] == 'l') && (str[i + 2] == 's')
&& (str[i + 3] == 'e')
&& (str[i+5] == ' ' || str[i+6] == '\n' || str[i+7] ==
'\t')) {
cycleCounter++;
}
}
}
fprintf(outputStream, "Broqt na operatorite za cikul e: %d\n",
cycleCounter);
}
void counter(FILE* inputStream, FILE* outputStream) {
char str[1000];
int Counter = 0;
unsigned i;
while (fgets(str, sizeof(str), inputStream) != NULL) {
for (i = 0; i < strlen(str); i++) {
{
if ((str[i-1] == ' ' || str[i-1] == '\n' || str[i-1] == '\t' || i==0))
{
Counter++;
}
}
}
}
fprintf(outputStream, "Broqt na redovete e: %d\n", Counter);
}
This is prefaced by my top comments.
That is, finding the if and the else is more easily done with strtok and strcmp.
And, to count rows/lines, simply doing fgets and counting or doing fgetc and counting the \n will work.
Hopefully, this will get you farther:
void
cycleOperatorsCounter(FILE *inputStream, FILE *outputStream)
{
char *bp;
char *tok;
char str[1000];
int cycleCounter = 0;
while (fgets(str, sizeof(str), inputStream) != NULL) {
bp = str;
while (1) {
tok = strtok(bp," \t\n");
if (tok == NULL)
break;
bp = NULL;
if (strcmp(tok,"if") == 0) {
cycleCounter++;
continue;
}
if (strcmp(tok,"else") == 0) {
cycleCounter++;
continue;
}
}
}
fprintf(outputStream, "Broqt na operatorite za cikul e: %d\n",
cycleCounter);
}
void
counter(FILE *inputStream, FILE *outputStream)
{
int Counter = 0;
// count number of lines
// NOTE: either of these should work:
#if 1
char str[1000];
while (fgets(str, sizeof(str), inputStream) != NULL)
++Counter;
#else
while (1) {
int chr = fgetc(inputStream);
if (chr == EOF)
break;
if (chr == '\n')
++Counter;
}
#endif
fprintf(outputStream, "Broqt na redovete e: %d\n", Counter);
}
I'm trying to read from a file using C and after shrinking the size using realloc I get corrupted data. I don't really see what the problem could be.
Here's the function that returns the string :
char *read_string(FILE *fichier) {
char car = 0;
size_t size = 1;
char *symbole = realloc(NULL, sizeof(char) * size);
char *s;
size_t len = 0;
if (!symbole)
return symbole;
else
s = symbole;
do {
car = getc(fichier);
} while (car != '"' && car != EOF);
if (car == EOF)
return EOFP;
else {
car = getc(fichier);
while (car != '"' ) {
s[len] = car;
car = getc(fichier);
len++;
if (len == size) {
symbole = realloc(s, sizeof(char) * (size += 1));
if (!symbole)
return symbole;
else
s = symbole;
}
}
s[len] = '\0' ;
symbole = realloc(s, sizeof(char) * len);
if (!symbole) {
printf("WTF");
return symbole;
} else
s = symbole;
return s;
}
}
My main function is:
int main(int argc, char *argv[]) {
FILE *fichier = NULL;
fichier = fopen("C:/Users/Nabila K/Documents/test.json", "r");
if ((fichier != NULL)) {
while (feof(fichier) == 0) {
char *test = read_string(fichier);
if (test == NULL) {
printf("test == NULL\n");
exit(1);
} else
if (test == EOFP) {
} else {
printf("%s\n", test);
free(test);
}
}
fclose(fichier);
} else {
exit(EXIT_FAILURE);
}
return 0;
}
UPDATE
My json file looks something like this :
{
"KARIM BENNI" : {
"2017-08-07 09:50:50" : {
"Anomalie" : {
"description" : "Test",
"theme" : "Engins mobiles"
},
"date" : "2017-08-07",
"date_now" : "2017-08-07 09:50:50",
"entite" : "USINE LAMINAGE A FROID",
"etat" : "Cree",
"nb_personne" : 2,
"temps" : 5,
"visiteur" : "KARIM BENNI",
"visite" : "AHMED RABII",
"zone" : "COUPE"
}
}
}
There are multiple issues in your code:
char car = 0; is incorrect: you must define car as int to correctly distinguish all values returned by getc(), especially EOF.
while (feof(fichier) == 0) is always wrong. Learn why there: Why is “while ( !feof (file) )” always wrong?
EOFP is not defined, you should probably use NULL instead for more clarity.
the final realloc() to shrink the allocated block is one byte too short. You must keep len+1 bytes for len characters plus the null terminator.
Here is a simplified and corrected version:
#include <stdio.h>
#include <stdlib.h>
char EOFP[1]; /* special value used to signal end of file */
char *read_string(FILE *file) {
int c;
size_t size, len;
char *symbol;
char *s;
while ((c = getc(file)) != '"') {
if (c == EOF)
return EOFP;
}
size = 16;
len = 0;
symbol = malloc(size);
if (symbol == NULL) {
/* allocation failure */
return NULL;
}
while ((c = getc(file)) != '"') {
if (c == EOF) {
/* premature end of file in the middle of a string */
free(symbol);
return EOFP;
}
if (len + 2 < size) {
size += size;
s = realloc(symbol, size);
if (s == NULL) {
/* allocation failure */
free(symbol);
return NULL;
}
symbol = s;
}
symbol[len++] = c;
}
symbol[len] = '\0';
s = realloc(symbol, len + 1);
return s ? s : symbol;
}
int main(int argc, char *argv[]) {
FILE *file = fopen("C:/Users/Nabila K/Documents/test.json", "r");
if (file != NULL)) {
char *test;
while ((test = read_string(file)) != EOFP) {
if (test == NULL) {
printf("test == NULL\n");
exit(1);
} else {
printf("%s\n", test);
free(test);
}
}
fclose(file);
} else {
exit(EXIT_FAILURE);
}
return 0;
}
Notes:
Parsing the full JSON syntax for strings would be required if the strings can contain escaped characters such as \" or \n, \\ etc.
My code is giving glibc error.Can someone please point out my mistake.
This code is used to tokenize words. How do i solve these problems using GDB or any other tool that can be helpful. The code is given below
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
#include <string.h>
struct token
{
char *token;
int length;
};
void freeing(gpointer item)
{
free(((struct token*)item)->token);
}
int main(int argc, char* argv[])
{
int start1 = 0, start2 = 0, i =0;
struct token *tk = NULL;
char line[256], *temp = NULL;
FILE *fp1 = NULL;
FILE *fp2 = NULL;
GSList *list = NULL, *iterator = NULL;
fp1 = fopen(argv[1], "r");
fp2 = fopen(argv[2], "w+");
if (NULL == fp1)
{
fprintf(stderr,"cant open %s",argv[1]);
return 1;
}
if (NULL == fp2)
{
fprintf(stderr,"cant open %s",argv[2]);
return 1;
}
while (1)
{
if (NULL == fgets(line, 255, fp1))
break;
tk = (struct token *)malloc(sizeof(struct token));
start1 = -1; start2 = -1;
for(temp = line,i = 0; temp[i] != '\n'; i++)
{
if ((temp[i] == ',') || (temp[i] == ' ') || (temp[i] == ';') || (temp[i] == '.'))
start2 = i;
if (start1 == start2)
continue;
tk->token = strndup(line + (start1+1), start2 - (start1+1));
tk->length = strlen(tk->token);
list = g_slist_append(list, tk);
start1 = start2;
}
tk->token = strndup(line + (start1+1), strlen(line));
tk->length = strlen(tk->token);
printf("\ntk->length : %d\n",tk->length);
list = g_slist_append(list, tk );
}
for (iterator = list; iterator; iterator = iterator->next)
{
printf("%s -> ",((struct token *)(iterator->data))->token);
printf("%d\n",((struct token*)iterator->data)->length);
}
g_slist_foreach(list, (GFunc)freeing, NULL);
fclose(fp1);
fclose(fp2);
return 0;
}
the following code has the major problems fixed, but not the logic errors in the loop :
for(int i=0, temp = line; temp[i] != '\n'; i++)
{
...
}
tk->token = strndup(line + (start1+1), strlen(line));
tk->length = strlen(tk->token);
printf("\ntk->length : %d\n",tk->length);
list = g_slist_append(list, tk );
the suggested fixes for the majority of the problems in the posted code are corrected in the following:
added final call to g_slist_free(list); so all the instances of the struct token are returned to the heap.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
#include <string.h>
#define MAX_LINE_LEN (256)
struct token
{
char *token;
int length;
};
void freeing(gpointer item)
{
free(((struct token*)item)->token);
}
int main(int argc, char* argv[])
{
if( 3 != argc )
{ // then incorrect number of command line arguments
fprintf( stderr, "USAGE: %s <inputfile> <outputfile>\n", argv[0]);
exit( EXIT_FAILURE );
}
// implied else, correct number of command line arguments
FILE *fp1 = NULL;
FILE *fp2 = NULL;
if( NULL == (fp1 = fopen(argv[1], "r") ) )
{ // then fopen failed
fprintf( stderr, "fopen for %s for read failed\n", argv[1]);
exit( EXIT_FAILURE );
}
// implied else, fopen successful
if( NULL == (fp2 = fopen(argv[2], "w+") ) )
{ // then fopen failed
fprintf( stderr, "fopen for %s for write failed\n", argv[2]);
fclose( fp1 ); // cleanup
exit( EXIT_FAILURE );
}
// implied else, fopen successful
GSList *list = NULL;
GSList *iterator = NULL;
char line[ MAX_LINE_LEN ];
struct token *tk = NULL;
char *temp = NULL;
while ( fgets(line, sizeof(line), fp1) )
{
if( NULL == (tk = malloc(sizeof(struct token)) ) )
{ // then malloc failed
perror( "malloc for struct token failed");
fclose( fp1 );
fclose( fp2 );
exit( EXIT_FAILURE );
}
// implied else, malloc successful
size_t start1 = 0;
size_t start2 = 0;
temp = line;
for(size_t i=0; temp[i] != '\n'; i++)
{
if ((temp[i] == ',') || (temp[i] == ' ') || (temp[i] == ';') || (temp[i] == '.'))
start2 = i;
if (start1 == start2)
continue;
tk->token = strndup(line + (start1+1), start2 - (start1+1));
tk->length = (int)strlen(tk->token);
list = g_slist_append(list, tk);
start1 = start2;
} // end for
tk->token = strndup(line + (start1+1), strlen(line));
tk->length = (int)strlen(tk->token);
printf("\ntk->length : %d\n",tk->length);
list = g_slist_append(list, tk );
} // end while
for (iterator = list; iterator; iterator = iterator->next)
{
printf("%s -> ",((struct token *)(iterator->data))->token);
printf("%d\n",((struct token*)iterator->data)->length);
}
g_slist_foreach(list, (GFunc)freeing, NULL);
g_slist_free(list);
fclose(fp1);
fclose(fp2);
return 0;
}
My program compares two text files and puts the differences in file one in a third text file. However, when my file one's size is larger than my file two's size a 'ÿ' character is placed at the end of the third file. For example suppose file one consists of "I like pickles." and file two consists of "I like dogs." then the third file will consist of "pickles.ÿ". Is there a way to get rid of this? And why is this happening? Here is my program:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int ch1, ch2;
int size1, size2;
FILE *fh1, *fh2, *diffone=stdout;
if( argc<3 ) {
printf("need two file names\n"); return(1);
}
if(!(fh1 = fopen(argv[1], "r"))) {
printf("cannot open %s\n",argv[1]); return(2);
}
if(!(fh2 = fopen(argv[2], "r"))) {
printf("cannot open %s\n",argv[2]); return(3);
}
if(argc>3) {
if(!(diffone = fopen(argv[3], "w+"))) {
printf("cannot open %s\n",argv[3]); return(4);
}
}
fseek(fh1, 0, SEEK_END);
size1 = ftell(fh1);//gets size of fh1
fseek(fh1, 0, SEEK_SET);
fseek(fh2, 0, SEEK_END);
size2 = ftell(fh2);//gets size of fh2
fseek(fh2, 0, SEEK_SET);
while((!feof(fh1)) || (!feof(fh2)))
{
ch1=ch2='-';
if(!feof(fh1)) ch1 = getc(fh1);
if(!feof(fh2)) ch2 = getc(fh2);
if (size2 > size1)
{
if(ch1 != ch2 && (!feof(fh1)))
{
fprintf(diffone,"%c", ch1);
}
}
else
{
if (ch1 != ch2)
{
fprintf(diffone,"%c", ch1);
}
}
}
}
feof() only returns true after fgetc() has returned EOF (-1).
See Why is “while ( !feof (file) )” always wrong?
You are not doing any error checking on fgetc(), and you are not checking for EOF on fh2 when size1 > size2.
Try this instead:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int ch1, ch2;
int eof1 = 0, eof2 = 0;
FILE *fh1, *fh2, *diffone=stdout;
if (argc < 3) {
printf("need two file names\n");
return(1);
}
if (!(fh1 = fopen(argv[1], "r"))) {
printf("cannot open %s\n",argv[1]);
return(2);
}
if (!(fh2 = fopen(argv[2], "r"))) {
printf("cannot open %s\n",argv[2]);
return(3);
}
if (argc > 3) {
if (!(diffone = fopen(argv[3], "w+"))) {
printf("cannot open %s\n",argv[3]);
return(4);
}
}
while(1)
{
if (!eof1) {
ch1 = fgetc(fh1);
if (ch1 == EOF) {
if (ferror(fh1)) {
printf("cannot read from %s\n",argv[1]);
return(5);
}
eof1 = 1;
}
}
else {
ch1 = '-';
}
if (!eof2) {
ch2 = fgetc(fh2);
if (ch2 == EOF) {
if (ferror(fh2)) {
printf("cannot read from %s\n",argv[2]);
return(6);
}
eof2 = 1;
}
}
else {
ch2 = '-';
}
if ((eof1) && (eof2))
break;
if ((ch1 != ch2) || (eof1 != eof2)) {
if (fputc(ch1, diffone) == EOF) {
if (argc > 3) {
printf("cannot write to %s\n",argv[3]);
}
return(7);
}
}
}
return 0;
}
Check EOF after each fgetc().
Avoid using feof(). Recall feof() becomes true after an EOF was first returned from a read.
Instead of
while((!feof(fh1)) || (!feof(fh2))) {
if(!feof(fh1)) ch1 = getc(fh1);
if(!feof(fh2)) ch2 = getc(fh2);
Use
while (1) {
ch1 = fget(fh1);
ch2 = fget(fh2);
if (ch1 == EOF) {
if (ch2 == EOF) break;
ch1 = '-';
}
if (ch2 == EOF) {
ch2 = '-';
}
....
}
This problem occurs when you are trying to fetch from file first and then print
for example-
ch=fgetc(fp2);
while(ch!=EOF)
{
ch = fgetc(fp2);
fputc(ch, fp1);
}
INSTEAD DO-
ch=fgetc(fp2);
while(ch!=EOF)
{
fputc(ch, fp1);
ch = fgetc(fp2);
}