Im getting a lineshift when trying to build a string - c

Im trying to build a string to call a script with args, and one of the args is read from a file but im getting a lineshift and the output is like this
/home/glennwiz/develop/c/SnuPort/ExpGetConfig.sh xogs1a 3/37
> lastConfig.txt
i want the 3/37 and > lastConfig to be on the same line.
this is my code.
char getConfig[100] = "/home/glennwiz/develop/c/SnuPort/ExpGetConfig.sh ";
char filedumpto[50] = " > lastConfig.txt";
FILE* file = fopen("rport.txt","r");
if(file == NULL)
{
return NULL;
}
fseek(file, 0, SEEK_END);
long int size = ftell(file);
rewind(file);
char* port = calloc(size, 1);
fread(port,1,size,file);
strcat(getConfig, argv[1]);
strcat(getConfig, port);
strcat(getConfig, filedumpto);
printf(getConfig);
//system(getConfig);
return 0;
edit
i dumped the output to a file and opened it in vim to see and it sends a ^M after the variable, which is enter i believe? why does it do this iv tried the solutions under this post but its not working.
tester port print!!!!
/home/glennwiz/develop/c/SnuPort/ExpGetConfig.sh randa1ar2 5/48^M
> SisteConfig.txt
tester port print!!!!

The input file ("rport.txt") probably contains a newline. Strip whitespace from the end of the read input, and it should be ok.

The file probably ends with an end-of-line sequence.
Sleazy, brittle solution:
fread(port, 1,size-1, file); // If it's just a CR or LF
fread(port, 1,size-2, file); // If it's a combination of CRLF.
// your code continues here
A better, portable solution will do something like this:
char *port = calloc(size+1, sizeof(char)); // Ensure string will end with null
int len = fread(port, 1, size, file); // Read len characters
char *end = port + len - 1; // Last char from the file
// If the last char is a CR or LF, shorten the string.
while (end >= p) && ((*end == '\r') || (*end == '\n')) {
*(end--) = '\0';
}
Here's working code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char getConfig[100] = "/home/glennwiz/develop/c/SnuPort/ExpGetConfig.sh ";
const char *filedumpto = " > lastConfig.txt";
int main(char argc, char *argv[]) {
FILE *file = fopen("rport.txt", "r");
if (file == NULL) {
return 1;
}
fseek(file, 0, SEEK_END);
long int size = ftell(file);
rewind(file);
char *port = calloc(size+1, 1);
int len = fread(port, 1, size, file); // Read len characters
char *end = port + len - 1; // Last char from the file
// While the last char is a CR or LF, shorten the string.
while ((end >= port) && ((*end == '\r') || (*end == '\n'))) {
*(end--) = '\0';
}
strcat(getConfig, argv[1]);
strcat(getConfig, port);
strcat(getConfig, filedumpto);
printf("%s\n", getConfig);
return 0;
}

Related

How to implement MPI in my C program to read file & remove space from it

I am new to C, After 4 days, I finally managed to make a program that read a file and remove space from it. I need to also make it parallel using MPI in any way. I tried various solutions, but MPI does not seem straightforward, it is complex, can someone please help me a bit to move forward.
Here is my code. It first reads a text file, and then removes space and new line characters.
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
FILE* pInputFile;
int chr = 0;
int main()
{
FILE* fptr;
char c;
char filename[] = "Lorem.txt";
char* str, * strblank;
int i = 0;
errno_t err;
if ((err = fopen_s(&pInputFile, filename, "r")) == 0)
{
/*count the number of characters in file for file initialization*/
size_t pos = ftell(pInputFile); // Current position
fseek(pInputFile, 0, SEEK_END); // Go to end
size_t length = ftell(pInputFile); // read the position which is the size
fseek(pInputFile, pos, SEEK_SET); // restore original position
//creating dynamic array of file size
str = malloc(length * sizeof(char));
strblank = malloc(length * sizeof(char));
while ((chr = getc(pInputFile)) != EOF)
{
str[i] = chr;
i++;
}
i = 0;
printf("%s", str);
removespace(str, strblank);
printf("%s", strblank);
fclose(pInputFile);
}
else
{
fprintf(stderr, "Cannot open file, error %d\n", err);
}
return 0;
}
int removespace(char aj[500], char mj[500])
{
int i = 0, j = 0, len;
len = strlen(aj); // len stores the length of the input string
while (aj[i] != '\0') // till string doesn't terminate
{
if (aj[i] != ' ' && aj[i] != '\n') // if the char is not a white space
{
/*
incrementing index j only when
the char is not space
*/
mj[j++] = aj[i];
}
/*
i is the index of the actual string and
is incremented irrespective of the spaces
*/
i++;
}
mj[j] = '\0';
printf("\n\nThe string after removing all the spaces is: ");
return 0;
}

Ignoring user input when testing with unity

I have a chatbot program that uses a function called userInput() to get the input from the user.
I have to test the program for my project but I don't know how to input text into the function in the test program. Everything I have tried has stopped the automatic testing waiting for the user to type something.
Any help adding test phrases the user would say without stopping the testing program.
char *userInput()
{
char *str = NULL;
int ch;
size_t size = 0, len = 0;
while ((ch=getchar()) != EOF && ch != '\n') {
if (len + 1 >= size)
{
size = size * 2 + 1;
str = realloc(str, sizeof(char)*size);
}
str[len++] = ch;
}
if (str != NULL) {
str[len] = '\0';
}
return str;
}
I ran with anonmess's idea that you can input text from the user using an input file. I used an input file with the following lines:
testing input
testing input 2
The input file name is given through the command line. You can hard code the filename if you'd like.
#include <stdio.h>
#include <string.h>
int processInputFile(char *filename)
{
FILE *ifp;
char buffer[1024];
char *p;
if ((ifp = fopen(filename, "r")) == NULL)
{
fprintf(stderr, "Failed to open \"%s \" in processInputFile.\n", filename);
return -1;
}
while ((fgets(buffer, sizeof(buffer), ifp)) != NULL)
{
// remove newline character
p = strchr(buffer, '\n');
if (p != NULL)
*p = '\0';
// We can also remove the newline character by getting
// its length and chomping the last character
// int length = strlen(buffer);
// buffer[length - 1] = '\0';
printf("%s\n", buffer);
}
fclose(ifp);
}
int main(int argc, char **argv)
{
if (argc < 2)
{
printf("Proper syntax: ./a.out <n>\n");
return -1;
}
processInputFile(argv[1]);
return 0;
}
The file is read and the lines are printed. You can pass the string to another function within the while loop.

How to pass a char array to fopen_s

#include <stdio.h>
int main(void)
{
int i;
char name[20];
FILE * src;
FILE * des;
fgets(name,20,stdin);
fopen_s(&src,"배경사진.jpg", "rb");
fopen_s(&des,name,"wb");
char buf[20];
int readcnt;
if (src == NULL || des == NULL) {
puts("파일 오픈 실패!");
return -1;
}
while (1)
{
readcnt = fread((void*)buf, 1, sizeof(buf), src);
if (readcnt < sizeof(buf))
{
if (feof(src) != 0)
{
fwrite((void*)buf, 1, readcnt, des);
puts("파일복사 완료");
}
else
puts("파일복사 실패");
break;
}
i wanna get (new file's name to be copied) in cmd.
generally fopen_s(&des,"~.jpg", "wb"); is used.
but i used char array instead of "~.jpg".
how do i do to make program user can put..
If I understood your problem.
fgets(name,20,stdin);
fopen_s(&des,name,"wb");
Your fopen_s will fail as fgets adds line feed character to the name.
Hence you need to trim the line feed char from the name.
Example:
size_t len = strlen(name);
if (len > 0 && name[len - 1] == '\n')
name[len - 1] = '\0';
fopen_s(&des,name,"wb");

How come my fread returns an empty string?

When I write my string to file, I first write the length of the string as an int, followed by the string itself. Here is my code:
int wordLength = strlen(words);
fwrite(&wordLength,sizeof(int),1, outputFile);
fwrite(&words,sizeof(char),strlen(words), outputFile);
However, when I fread it back, I get an empty string. Here is my reading code:
int strLength;
fread(&strLength, sizeof(int), 1, f);
char* word = (char*) malloc(strLength*sizeof(char));
fread(&word, sizeof(char), strLength, f);
Why is this happening?
when I fread it back, I get an empty string. Here is my reading code:
Why is this happening?
fread(&strLength, sizeof(int), 1, f);
char* word = (char*) malloc(strLength*sizeof(char));
fread(&word, sizeof(char), strLength, f);
Code allocates insufficient memory. strLength*sizeof(char) is enough for the text yet not the terminating null character to make a string.
// char* word = (char*) malloc(strLength*sizeof(char));
char* word = malloc(strLength + 1u); // add 1
fread(&word, ...); is attempting to read data into the address of word, rather than into the memory just allocated.
// fread(&word, sizeof(char), strLength, f);
fread(word, sizeof *word, strLength, f); // drop &
The null character is never appended.
size_t count = fread(word, sizeof *word, strLength, f);
if (count != strLength) puts("Error");
else {
word[strLength] = '\0';
puts(word);
}
Notes:
Better to use size_t wordLength
Checking the return value of malloc() makes for good code.
size_t wordLength = strlen(words);
...
char* word = malloc(strLength + 1);
if (word == NULL) Hanlde_OutOfMemory();
Post does not show file open/closing details. Code may need to rewind(f) before reading data written.
This works on Ubuntu:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
FILE *outputFile;
FILE *inputFile;
char words[] = "This is a series of words";
int wordLength = strlen(words);
outputFile = fopen("outputFile", "w");
if ( outputFile == NULL )
{
perror("fopen failed: ");
exit(1);
}
fwrite(&wordLength,sizeof(int),1, outputFile);
fwrite(words,sizeof(char),strlen(words), outputFile);
fclose(outputFile);
inputFile = fopen("outputFile", "r");
if ( inputFile == NULL )
{
perror("fopen(2) failed: ");
exit(1);
}
int strLength = -99;
fread(&strLength, sizeof(int), 1, inputFile);
char* buff = (char*) malloc(strLength*sizeof(char));
fread(buff, sizeof(char), strLength, inputFile);
buff[strLength] = 0x00;
printf("Input Str: -->%s<--\n", buff);
}

Char* parse error from char array

I read a file and stock all characters like this:
void ReadFile()
{
int c;
FILE *file;
int string_size;
file = fopen("/userFiles/ex.txt", "r");
char * content;
if (file)
{
// Seek the last byte of the file
fseek(file, 0, SEEK_END);
// Offset from the first to the last byte, or in other words, filesize
string_size = ftell(file);
// go back to the start of the file
rewind(file);
// Allocate a string that can hold it all
content = malloc((string_size + 1) * sizeof(char));
int i = 0;
while ((c = getc(file)) != EOF)
{
//printf("%c",(char) c);
content[i] = (char) c;
i++;
}
content[string_size] = '\0';
printf("content: %s",content);
fclose(file);
}
else
{
printf("not load\n");
}
}
Problem is if i read each carachter i've got the content of the file but if i do:
printf("content: %s",content);
I got just a symbol and not text whereas i need to pass the content var with correct text in argument of a json reply.
This is the first line of the file (CRC32):
�ex.txt k��X� ?xml version="1.0" encoding="utf-8"?
I compiled and ran the following code and it shows no major problem when executed.
The compilable version I used is (cmdline: gcc main.c -Wall -Wextra -o main):
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
int c;
FILE *file;
int string_size;
file = fopen("plop", "r");
char * content;
if (file == NULL)
{
perror("fprintf");
return 1;
}
// Seek the last byte of the file
fseek(file, 0, SEEK_END);
// Offset from the first to the last byte, or in other words, filesize
string_size = ftell(file);
// go back to the start of the file
rewind(file);
// Allocate a string that can hold it all
content = malloc((string_size + 1) * sizeof(char));
int i = 0;
while ((c = getc(file)) != EOF)
{
//printf("%c",(char) c);
content[i] = (char) c;
i++;
}
content[string_size] = '\0';
printf("content: %s", content);
return 0;
}
Maybe your file has a binary content?
What is the symbol printed, that you mentioned?
I think you should use quotes "" around the content string:
printf("content: \"%s\"",content);

Resources